Best way for Retrieving data from more tables in Laravel

illuminami :

I am new to laravel and I have a simple question, I am writing the controllers for my application and i need to do one simple things, i have to return a model with data from more tables, how would you do this? for example: i need to return to the view a 'Comment' with the name of the 'User' that wrote the comment but the model 'Comment' has only the id of the 'User' in 'id_user', how do i return the comment with the name of the user?

Hamed Yarandi :

You should use the relationship between comment and user models,

I suggest you learning relationship first (in your case every user can have many comments)

Then you can use One To Many relationship

Then use 'With' and get every user with comments,

For instance :

$users = App\User::with('comment')->get();

foreach ($users as $user) {

   echo $user->comments->description;

}

Hope to help

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=278907&siteId=1