3

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
Mirza Obaid
  • 1,707
  • 3
  • 23
  • 35
Michael Mano
  • 3,339
  • 2
  • 14
  • 35
  • here is what you want http://stackoverflow.com/questions/13002626/laravels-blade-how-can-i-set-variables-in-a-template – Drudge Rajen Mar 22 '16 at 05:58
  • Thanks, So I meant is there any way of setting these from the controller or a view rather than a blade? From what you linked me i just swapped out the – Michael Mano Mar 22 '16 at 06:16
  • Blade donot had any way of doing it . So, i think that it is the best option . – Drudge Rajen Mar 22 '16 at 06:21
  • Personally I think the comment-style variable declaration is even messier than using plain PHP in the view. So far the latter is the way I solve it. – Ben Fransen Mar 22 '16 at 06:44

1 Answers1

0

found a solution to my issue if anyone else is ever looking for it.

public function getLastOnlineAttribute($value)
{
    $fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
    $thirtMinsAgo = \Carbon\Carbon::now()->subMinute(30);
    $lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($value))->diffForHumans();
    if ($value <= $fiveMinsAgo) {
        echo 'Last Active: '.$lastOnline.'';
    }
    else {
        echo 'Online Now';
    }

}

Basically add this into your model for the variable (eg, if its a $user->last_online it would go into the user model) , it is called a eloquent mutator if you are ever looking for more info, https://laravel.com/docs/master/eloquent-mutators

It grabs your data for the variable for instance {{ $user->last_online }}

Note that the Underscore is transformed into a CamelCase in the function name, the output is set at $value, you can then set variables inside of the function and mould the output however you wish, then in the blade you can get rid of all the extra crap and just use {{ $user->last_online }}

Michael Mano
  • 3,339
  • 2
  • 14
  • 35