Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Pass object through view and use in blade

Basically, I've a simple 'exp' column in my database and I want to use a function 'showLevel()' where I can pass in Auth::user->username as the argument instead of a static name. I'm struggling with how I can use either a function in an echo on my template or with an object.

public function index()
{
    $users = User::all();

    $level = $this->showLevel('test');

    return view('home')->with('users', $users)->with('showLevel', $level);
}

public function showLevel($username) {

    $level = DB::table('users')->where('username', $username)->pluck('exp');

    if ($level < 500) {
        return 1;
    } else if ($level > 500 && $level < 1000) {
        return 2;
    } else if ($level > 1000 && $level < 1500) {
        return 3;
    } else if ($level > 1500 && $level < 2000) {
        return 4;
    } else if ($level > 2000 && $level < 2500) {
        return 5;
    } else if ($level > 2500) {
        return 'MAX';
    }

}

I tried creating an object in home.blade.php.

$level = new HomeController;
$level->showLevel(Auth::user->username);

But that didn't seem to work. Can you pass objects in blade? I've been trying to look this up myself but maybe I'm wording it wrong. I'm stuck!

I basically want to be able to do something like {{ showLevel(Auth::user->username); }} in my home.blade.php to echo the level that's returned from the function.

like image 847
Vaughan Slater Avatar asked Jun 27 '15 16:06

Vaughan Slater


1 Answers

Yes, you can pass an object to blade. You use the compact method to achieve that:

return view('home')->with(compact('users'));

In your blade you can access users like this:

@if ($users)
   @foreach($users as $user)
      {{ $user->name }}
   @endforeach
@endif
like image 80
iep Avatar answered Sep 19 '22 07:09

iep