In this tutorial we will learn what is relation in laravel with example.
What is Relation In Laravel with Example
In Laravel, a relation refers to the association between two database tables. It allows you to define how two tables are related to each other and retrieve data from them in a structured and efficient way.
There are several types of relations in Laravel, including:
-
One-to-One: In this type of relation, each record in one table is associated with only one record in another table. For example, a user may have one profile.
-
One-to-Many: In this type of relation, each record in one table can be associated with many records in another table. For example, a user can have many posts.
-
Many-to-Many: In this type of relation, multiple records in one table can be associated with multiple records in another table. For example, a user can have many roles, and a role can belong to many users.
Here's an example of a one-to-many relationship between the User
and Post
models in Laravel:
// User Model
class User extends Model
{
/**
* Get the posts for the user.
*/
public function posts()
{
return $this->hasMany(Post::class);
}
}
// Post Model
class Post extends Model
{
/**
* Get the user that owns the post.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
With this relationship defined, you can easily retrieve all posts for a user:
$user = User::find(1);
$posts = $user->posts;
Or retrieve the user who owns a specific post:
$post = Post::find(1);
$user = $post->user;