How to add query on relational data in laravel?

by filiberto , in category: PHP Frameworks , 6 months ago

How to add query on relational data in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 6 months ago

@filiberto 

In Laravel, you can add queries on relational data using Eloquent, the ORM provided by Laravel. Here is an example of how you can add a query on relational data:


Assuming you have two models: User and Post, and there is a one-to-many relationship between them (one user can have many posts).

  1. Define the relationship in the models:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// User.php
public function posts()
{
    return $this->hasMany(Post::class);
}

// Post.php
public function user()
{
    return $this->belongsTo(User::class);
}


  1. Query the relational data using Eloquent:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$user = User::find($userId);

// Get all posts for a specific user
$posts = $user->posts;

// Get all posts for a specific user where the post has more than 100 likes
$posts = $user->posts()->where('likes', '>', 100)->get();

// Get all posts for a specific user with the user's name
$posts = Post::select('posts.*')
    ->join('users', 'posts.user_id', '=', 'users.id')
    ->where('users.id', $userId)
    ->get();


By using Eloquent relationships and query methods, you can easily add queries on relational data in Laravel.