Vaughan Slater
Vaughan Slater

Reputation: 115

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.

Upvotes: 7

Views: 42367

Answers (4)

Adam Phillips
Adam Phillips

Reputation: 233

The shorthand for compact and with would be:

return view('home', ['data' => $data,...]);

This is works just fine for all of my views where this is needed.

Upvotes: 0

Panda Zhang
Panda Zhang

Reputation: 11

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

than you can foreach it on your blade.php

Upvotes: 1

Nilesh
Nilesh

Reputation: 934

Try something like this:

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

and Return Blade::

 return view('home')->with(['data'=>$data]);

Now, In Your Blade You Can Use $data

Upvotes: 4

iep
iep

Reputation: 651

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

Upvotes: 8

Related Questions