php - Laravel - 通过 View 传递对象并在 Blade 中使用

标签 php laravel laravel-blade

基本上,我的数据库中有一个简单的“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';
    }

}

我尝试在 home.blade.php 中创建一个对象。

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

但这似乎没有用。你能在 Blade 中传递物体吗?我一直在尝试自己查找,但也许我的措辞有误。我卡住了!

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

最佳答案

是的,您可以将对象传递给 blade。您使用紧凑的方法来实现:

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

在您的 Blade 中,您可以像这样访问用户:

@if ($users)
   @foreach($users as $user)
      {{ $user->name }}
   @endforeach
@endif

关于php - Laravel - 通过 View 传递对象并在 Blade 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31090665/

相关文章:

php - 使用 JQuery 消失的 div - 我如何阻止它在下次打开页面时重新加载

php - Parse Server - 如何在 Heroku 上启用 REST API key

php - 如何不使用 Doctrine 将对象持久化到实体内部?

php - Laravel 中组合两个表的模型

php - "Heavy"并发用户数 Nginx - Laravel - Google 计算引擎

php - 连接表的 Codeigniter 计数结果

php - 如何在 Laravel Eloquent Collection 数组前加上键值对?

javascript - 防止 Blade php函数编码符号

php - 无法从 laravel 中的 session 获取 $id

php - 当我添加我的新代码然后在 laravel 中收到错误 "This cache store does not support tagging"?