How to access relationship attributes in Laravel?

Asked

Viewed 981 times

2

In the image below we see a typical example of Collection in Laravel. We may see in Relations there is another Collection.

How do I access this in the View?

I’m doing so in Controller:

$users = User::with(['logs' => function($q) use ($startAt, $endAt){
    $q->whereDate('created_at', '>=', $startAt->format('Y-m-d H:i:s'));
    $q->whereDate('created_at', '<=', $endAt->format('Y-m-d H:i:s'));
}]);

I know at View I can make one:

@foreach($users as $user)

@endforeach

The question is how can I get the Collection 'Logs' inside the Foreach for that user who is passing there.

inserir a descrição da imagem aqui

Groupby and Filter

$videoList = $user['logs']->filter(function($q){ 
    return $q->content->type == 'video'; 
})->groupBy('content_id');
  • You cannot pull the $users['Relations']['logs'] and loop from there ?

  • I can. But I’m using the same object for several things. But I’m going to test the suggestions. I haven’t touched Lavarel for a while...

  • loopa as you did, take the array_key_exist (or some similar in the Laravel), and if you hit the key with loopa Relations again inside the already open loop to get the logs#items, then you do not need to open separate, but end up doing a more check

2 answers

3


With that you should be able to return all the logs contained in $user.

@foreach($users as $user)
    @foreach ($user->relations as $logs)
     $logs['logs']
    @endforeach
@endforeach
  • Before doing this I need to make a Filter and a Groupby in Collection Logs. But Groupby is not working.

  • So@Miguel, it works. However, don’t take my filter into account in Controller. That’s what’s breaking me...

  • Logs are inside Relations, according to the image that he posted, so I went through the array with the user , to then go through $user->Relations and return the log data.

  • Then you have to make another go inside the Relations' for?

  • @Diegosouza , how are you trying to make the groupBy ?

  • I posted on the question.

  • You can try something like this: $videoList = $user['logs']->filter(Function($q){ Return $q->content->type == 'video'; })->groupBy('content_id')->Pluck('content_id');

Show 2 more comments

1

Within your loop you can get relationship Collection and then use Laravel methods to treat your Collection.

In the following link you can consult the methods:

https://laravel.com/docs/5.5/eloquent-collections

In case your code would look like the following:

@foreach($users as $user)
   <?php
      $user->logs()->groupBy('coluna_que_você_deseja_agrupar');
   ?>
@endforeach

See the documentation for how groupBy works.

Or if you only want to use Collection logs, your code would look like this:

@foreach($users as $user)

   @foreach ($user->logs() as $log )

   @endforeach

@endforeach

Browser other questions tagged

You are not signed in. Login or sign up in order to post.