Laravel Eloquent BelongsTo Relationship - Explained

 How to use BelongsTo relationship in Laravel Eloquent

Laravel Eloquent BelongsTo Relationship - Explained

Laravel is one of the best frameworks among all the php frameworks due to its lots of features and inbuilt functionalities which makes our development more faster and efficient and one of these best feature is Eloquent.

Eloquent provides us the mechanism to deal with multiple table joins in a very easy and efficient manner by handling the complexity at its own end. Eloquent provides lots of relationship models line one to one, one to many and many to many etc.

What is BelongsTo Relationship:

The BelongsTo relationship is particularly useful when establishing a connection where one table "belongs to" another. In simpler terms, it reflects a parent-child relationship, with the child table containing a foreign key that references the parent table's primary key.

In our article of HasMany relationship article we have already seen how we are connecting parent table with its child table and get the results. In BelongsTo relationship we are doing the reverse kind of thing, where we are connecting child table with parent table and by using child Model we will fetch its parent tables data.

For example. Assume that we have to table named users and posts. Each user can have multiple posts. For these two tables we have separate models as well named User and Post. Now we will see how can use Post model and access its Parent data that is User.

Table structure of users table:

Laravel Eloquent BelongsTo Relationship - Explained

Table structure of posts table:

Laravel Eloquent BelongsTo Relationship - Explained

Now we have our two tables and we need to perform BelongsTo relationship. First we need to create two models for these two table. You can use the following command to create your models.

php artisan make:model User

User Model:

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Post;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    public function getPost(){
        return $this->hasMany(Post::class,'user_id','id');
    }
}

Post Model:

<?php

namespace App\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory;
    public function getUser(){
        return $this->belongsTo(User::class,'id','user_id');
    }
}

Create a route:

Route::get('getusers',[HomeController::class,'getUsers'])->name('users.getusers');

Code on Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Elastic\Elasticsearch\ClientBuilder;
use App\Models\Post;

class HomeController extends Controller
{
    public function getUsers(){
        try{
            $users = Post::with('getUser')->get();
            return $users;
        }catch(\Exception $e){
            return false;
        }
    }
}

Output:

Laravel Eloquent BelongsTo Relationship - Explained


Previous Post Next Post

Contact Form