我想在一个视图中使用来自表单的输入并将结果打印到另一个视图中。我收到以下错误:未定义的变量:用户预先感谢!
我用来获取电子邮件地址的表单(在称为“仪表板”的视图中):
...
<div class="search">
<header><h3>Search Friend</h3></header>
<form action="{{ route('search.friend') }}" method="post">
<div class="form-group">
<input class="form-control" type="text" name="email" id="email" placeholder="Friend's email">
</div>
<button type="submit" class="btn btn-primary">Post</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
</div>
...
将数据从“仪表板”发送到Controller的路径:
Route::post('/searchfriend',[
'uses' => 'FriendController@getSearchFriend',
'as' => 'search.friend',
'middleware' => 'auth'
]);
我使用电子邮件查找用户的控制器:
class FriendController extends Controller
{
public function getSearchFriend(Request $request)
{
$this->validate($request,[
'email' => 'required | email'
]);
$email = $request['email'];
$users = User::where('email',$email)->get();
return view('userlist',['$users' => $users]);
}
}
将结果发送到“用户列表”视图的途径:
Route::get('/userlist',[
'uses' => 'FriendController@getSearchFriend',
'as' => 'userlist',
'middleware' => 'auth'
]);
最后,“用户列表”视图:
@extends('layouts.master')
@section('title')
Users
@endsection
@section('content')
<section class="row new-post">
<div class="col-md-6 col-md-offset-3">
<header><h3>Users</h3></header>
<div class="userlist">
<header><h2>Click to Add Friend</h2></header>
@foreach($users as $user)
<a href="" class="" id="">Name: {{ $user->username }}</a>
@endforeach
</div>
</div>
</section>
@endsection
答案 0 :(得分:2)
更改:
class FriendController extends Controller
{
public function getSearchFriend(Request $request)
{
$this->validate($request,[
'email' => 'required | email'
]);
$email = $request['email'];
$users = User::where('email',$email)->get();
return view('userlist',['$users' => $users]);
}
}
收件人:
class FriendController extends Controller
{
public function getSearchFriend(Request $request)
{
$this->validate($request,[
'email' => 'required | email'
]);
$email = $request['email'];
$users = User::where('email',$email)->get();
return view('userlist',['users' => $users]);
}
}
将变量名称传递给视图时,不需要$。
答案 1 :(得分:0)
@Ryan J Field是正确的。另外,您可以通过许多不同的方式传递变量。例如-
return view('userlist')->with('users', $users);
或者,
return view('userlist', compact(users));