How to access relationship attribute in Laravel?

1

In the image below we see a typical example of Collection in Laravel. We can see in relations another collection.

How do I access this in View?

I'm doing so on the 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 that in View I can make one:

@foreach($users as $user)

@endforeach

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

GroupBy and Filter

$videoList = $user['logs']->filter(function($q){ 
    return $q->content->type == 'video'; 
})->groupBy('content_id');
    
asked by anonymous 02.10.2017 / 18:43

2 answers

2

With this 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
    
02.10.2017 / 18:56
1

Within your loop you can get the relationship collection and then use laravel's methods to handle your collection.

In the following link you can consult the methods:

link

In case your code would look similar to 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 just want to use the collection of logs, your code would look like this:

@foreach($users as $user)

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

   @endforeach

@endforeach
    
03.10.2017 / 15:17