How to make a relation between 2 tables in laravel?

Member

by deron , in category: PHP Frameworks , a month ago

How to make a relation between 2 tables in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 15 days ago

@deron 

To create a relationship between two tables in Laravel, you can use Eloquent models and define relationships between them. Here's how you can do it:

  1. Define the Eloquent models for each table. You can create a model for each table by running the following Artisan command in the terminal:
1
php artisan make:model TableName


Replace TableName with the name of your table.

  1. In each model class, define the relationships with other models using Eloquent's methods. For example, if you have a User model and a Post model, and you want to create a one-to-many relationship (a user can have many posts), you would define the relationship as follows:


In the User model:

1
2
3
4
public function posts()
{
    return $this->hasMany(Post::class);
}


In the Post model:

1
2
3
4
public function user()
{
    return $this->belongsTo(User::class);
}


  1. Use the relationships in your code. You can now use the relationships you defined in your Eloquent models to fetch related data. For example, to fetch all posts belonging to a user with the ID of 1, you can do something like this:
1
2
$user = User::find(1);
$posts = $user->posts;


By defining relationships between Eloquent models in Laravel, you can easily access related data and use it in your application.