How to make relationship between two tables in laravel?

Member

by samara , in category: PHP Frameworks , 2 months ago

How to make relationship between two tables in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 2 months ago

@samara 

To make a relationship between two tables in Laravel, you can use Eloquent ORM, which is an Object-Relational Mapping system included with Laravel. Eloquent allows you to define relationships between different database tables by defining model classes and using methods to establish the relationships.


Here is an example of how to create a relationship between two tables in Laravel:

  1. Create two migration files to create the two tables in your database. For example, let's say you have a "users" table and a "posts" table. You can run the following commands to create the migration files:
1
2
php artisan make:migration create_users_table
php artisan make:migration create_posts_table


  1. Define the schema for the "users" and "posts" tables in their respective migration files.
  2. Run the migrations to create the tables in your database by running the following command:
1
php artisan migrate


  1. Create model classes for the "users" and "posts" tables by running the following commands:
1
2
php artisan make:model User
php artisan make:model Post


  1. Define the relationships between the two tables in the model classes. For example, if you want to establish a one-to-many relationship where a user can have multiple posts, you can define the relationship in the User model class like this:
1
2
3
4
5
6
7
class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}


And in the Post model class, you can define the inverse relationship like this:

1
2
3
4
5
6
7
class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}


  1. With the relationships defined in the model classes, you can now use Eloquent's methods to retrieve related data. For example, you can fetch a user's posts like this:
1
2
$user = User::find(1);
$posts = $user->posts;


This is a basic example of how to create a relationship between two tables in Laravel using Eloquent ORM. There are other types of relationships you can define such as one-to-one, many-to-many, and polymorphic relationships, which can be implemented in a similar way.