How to make a relation in laravel in model?

Member

by lily , in category: PHP Frameworks , 3 months ago

How to make a relation in laravel in model?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 3 months ago

@lily 

To create a relation in Laravel model, you can use Eloquent relationships. Eloquent provides several types of relationships such as One-to-One, One-to-Many, Many-to-Many, Has-Many-Through, Polymorphic, and many more.


Here is an example of how to create a One-to-Many relationship in a Laravel model:

  1. Define the relationship in the model class by creating a method that returns the relationship:
1
2
3
4
5
6
7
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}


  1. Then, you can access the related records using the defined relationship method in your code:
1
2
$post = Post::find(1);
$comments = $post->comments;


This will return all the comments related to the given post.


You can define other types of relationships using Eloquent methods like hasOne, belongsTo, belongsToMany, etc. You can refer to the Laravel documentation for more details on Eloquent relationships: https://laravel.com/docs/8.x/eloquent-relationships.