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