Search code examples
phplaravellaravel-blade

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.


Solution

  • 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