php Laravel - 通过视图传递对象并在刀片中使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31090665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:14:03  来源:igfitidea点击:

Laravel - Pass object through view and use in blade

phplaravellaravel-blade

提问by Vaughan Slater

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->usernameas 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.

基本上,我的数据库中有一个简单的“exp”列,我想使用一个函数“showLevel()”,我可以在其中Auth::user->username作为参数而不是静态名称传入。我正在努力解决如何在我的模板或对象的回声中使用函数。

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.

我尝试在 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.

我基本上希望能够{{ showLevel(Auth::user->username); }}在我的 home.blade.php 中做一些事情来回显从函数返回的级别。

采纳答案by Nilesh

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

现在,在你的刀片中你可以使用 $data

回答by iep

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

回答by Panda Zhang

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

than you can foreach it on your blade.php

比你可以在你的blade.php 上 foreach