Consult select with eloquent in Laravel

0

I'm starting with Laravel and I have two simple entities that are users and notas , which are related in the following way:

Users

public function notes()
{
  return $this->hasMany('App\Note');
}

Notes

public function user()
{
  return $this->belongsTo('App\User');
}

Now, within my notes controller with eloquent, I would like to return all the records that I have in the notes table, but instead of receiving the id of the user in each record, I would like to return the name of this. Is there something that I have to specify in the relationship of both entities or should I simply adjust something in my query as a join? Or in eloquent there is another way to do it? At this moment I am using this:

$notes = Note::orderBy('id', 'desc')->get();
    
asked by FeRcHo 16.01.2018 в 14:51
source

1 answer

4

You recover all the notes and samples with a foreach:

$notes = Note::orderBy('id', 'desc')->with('user')->get();

To see the user's name:

foereach($notes as $note){
     echo $nota->id .' => '. $nota->desc .' => '.$nota->user->nombreUser;
}

//Donde *nombreUser es el nombre de la columna en la que guardas el nombre de usuario en la tabla users.

To return JSON:

return $notes->toJson();

This code will show on the screen the id of the note, its description and the name of the user.

    
answered by 16.01.2018 в 14:57