Laravel Eloquent Relationships Tutorial Example Step by Step

••• Laravel Eloquent Relationships Tutorial Example Step by Step

Laravel Eloquent Relationships Tutorial Example Step by Step is today’s leading topic. We will use the Laravel 5.5 in this tutorial. Eloquent relationships defined as the methods on your Eloquent model classes. It is like Eloquent models themselves; relationships also serve as an essential query builders, representing the relationships as methods provide powerful method chaining and querying capabilities.

Database tables are often related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Laravel Eloquent Relationships makes managing and working with these relationships easy, and supports several different types of relationships:

Eloquent makes managing and working with these relationships smooth, and supports several different types of relationships:

Laravel Eloquent Relationships


We are downloading one Laravel 5.5 Project, and then we start with an example.

Step 1: Configure Laravel 5.5 Project

Install by the following command.

composer create-project laravel/laravel --prefer-dist Relationships

Set up the MySQL database. and then edit the .env file like that.

Step 2: Edit the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=relationship_db
DB_USERNAME=your_username
DB_PASSWORD=your_password

Now, we need to make Two tables to build the relationships between them.

  1. Users Table
  2. Posts Table
php artisan make:migration create_users_table
php artisan make:migration create_posts_table

Define the Schema of these tables.

Users Table Scheme

<?php

// create_users_table

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->string('password');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Posts Table Scheme

<?php

// create_posts_table

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug')->unique();
            $table->string('status');
            $table->integer('user_id');
            $table->integer('category_id');
            $table->integer('view');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Next, type the following command for migrate the both table and its relationship.

php artisan migrate

It will create all five tables in the database.

Step 3: Make models for all these new two tables.

Type the following command.

php artisan make:model User
php artisan make:model Post

One To One Relationship


A one-to-one relationship is a very basic relation. For example, a User model might be associated with one Post. To define this relationship, we place a post method on the User model. The post method should call the hasOne method and return its result:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the post record associated with the user.
     */
    public function post()
    {
        return $this->hasOne('App\Post');
    }
}

The first argument passed to the hasOne method is the name of the related model. Once the relationship is defined, we may retrieve the related record using Eloquent’s dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:

$post= User::find(1)->post;

Eloquent determines the foreign key of the relationship based on the model name. In this case, the Post model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:

return $this->hasOne('App\Post', 'foreign_key');

Additionally, Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent. In other words, Eloquent will look for the value of the user’s id column in the user_id column of the Post record. If you would like the relationship to use a value other than id, you may pass a third argument to the hasOne method specifying your custom key:

return $this->hasOne('App\Post', 'foreign_key', 'local_key');

One To One Relationship Inverse