Laravel 5.2 correct way to use variables in blade

Viewed 667

So I know about passing variables via the controller for instance if its a query array I will do

public function index()
{
    $query = Request::get('q');
    if ($query) {
        $users = User::where('username', 'LIKE', "%$query%")->get();
    }

    return view('view', compact('users'));
}

And when on the blade I will do

 @if( ! empty($users))     
    @foreach($users as $user)
        {{ $user->username }}
    @endforeach
 @endif

Now my question is how do I set a variable using a variable from the foreach? at the moment I am using PHP inside of the blade template file but I feel this is messy, here is what I have

@if( ! empty($users))     
    @foreach($users as $user)
     <?php 
        $lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($user->last_online))->diffForHumans();
        $fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
     ?>
        {{ $user->username }}
        @if ($user->last_online <= $fiveMinsAgo)
            {{ $lastOnline }}
        @else 
            Online Now
        @endif
    @endforeach
@endif
1 Answers
Related