laravel 未定义变量:用户
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43303703/
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
laravel Undefined variable: user
提问by BARNOWL
Just to preface this, i have went through most of the answers that are aligned to my question, pretty much i have a undefined variablefor user.
只是作为序言,我已经浏览了与我的问题一致的大多数答案,几乎我有一个未定义的用户变量。
I want to be able to display the registered user on the dashboard, i used this code before and it worked but not for this application.
我希望能够在仪表板上显示注册用户,我之前使用过此代码并且它有效但不适用于此应用程序。
Undefined variable: user (View: /Applications/MAMP/htdocs/eli/resources/views/dashboard.blade.php)
Here is my code,
这是我的代码,
UserController.php
用户控制器.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use App\Http\Requests;
class UserController extends Controller
{
public function getWelcome()
{
return view('welcome');
}
public function getDashboard()
{
$users = User::all();
return view('dashboard', compact('users'));
}
public function userSignUp(Request $request)
{
$this->validate($request, [
'email' => 'required|email|unique:users',
'first_name' => 'required|max:120',
'password' => 'required|min:4'
]);
$email = $request['email'];
$first_name = $request['first_name'];
$password = bcrypt($request['password']);
$user = new User();
$user->email = $email;
$user->first_name = $first_name;
$user->password = $password;
$user->save();
return redirect()->route('dashboard');
}
public function postSignin(Request $request)
{
$remember = $request->input('remember_me');
if(Auth::attempt(['email'=> $request['email'], 'password' => $request['password']], $remember )){
return redirect()->route('dashboard');
}
return redirect()->back();
}
}
dashboard.blade.php
仪表盘.blade.php
@extends('layouts.layout')
@section('title')
Dashboard
@endsection
@section('content')
<div class="container eli-main">
<div class="row">
<div class="col-md-6 col-md-12">
<h1>{{$user->username}}</h1>
</div>
</div>
@endsection
采纳答案by Alexey Mezenin
You're passing $users
collection to the view, so you need to iterate over it if you want to display names of all users:
您正在将$users
集合传递给视图,因此如果要显示所有用户的名称,则需要对其进行迭代:
@foreach ($users as $user)
{{ $user->username }}
@endforeach
If you want to display name of authenticated user, just do this instead:
如果要显示经过身份验证的用户的名称,只需执行以下操作:
{{ auth()->user()->username }}