0
votes

Database

i have 3 tables users, posts and post_user

users table     projects table      project_user table
---------       ---------           --------------------
id | name       id | name           project_id | user_id
---------       ---------           --------------------
1  | user1      1  | pr1            1      |    1
2  | user2      2  | pr2            2      |    1
---------       3  | Pr3            3      |    2
                ---------          --------------------

Models

User Model


public function projects(){
    return $this->belongsToMany(Project::class);
}

Project Model


public function users(){
    return $this->belongsToMany(User::class);
}

The project is written by laravel 8.x Now in controller and view how to get all the projects which belongs specific user id. all i need is to display the projects of the logged in user using laravel.

1
Please show us what you tryied so farporloscerros Ψ

1 Answers

1
votes
$projects = App\User::find(5)->projects;

This will get all projects for a user of ID 5.

You of course need to import the class like App\User::find, or have use App\User in top of PHP file.

For further clarity on what is going on:

  • User::find(5) - returns the user with ID 5 (or whatever is your primary key field)
  • ->projects is a magic method which will return all results for the relationship defined in the projects() method of the User class.
  • Had we done ->projects() (instead of ->projects) we would instead receive the Query Builder object for the relationship which we could chain more query arguments onto (such as ->where() or ->limit(x) etc) and finally could call ->get() to return the results (Collection) of the query.