将请求参数传递给 View - Laravel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34483859/
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
Passing request parameter to View - Laravel
提问by moh_abk
Is it possible to pass a route
parameter to a controller to then pass to a view in laravel
?
是否可以将route
参数传递给控制器然后传递给视图laravel
?
Example;
例子;
I have the route below;
我有下面的路线;
Route::get('post/{id}/{name}', 'BlogController@post')->name('blog-post');
I want to pass {id}
and {name}
to my view so in my controller
我想在我的控制器中传递{id}
并传递{name}
给我的视图
class BlogController extends Controller
{
//
public function post () {
//get id and name and pass it to the view
return view('pages.blog.post');
}
}
采纳答案by Marcin Nabia?ek
You can use:
您可以使用:
public function post ($id, $name)
{
return view('pages.blog.post', ['name' => $name, 'id' => $id]);
}
or even shorter:
甚至更短:
public function post ($id, $name)
{
return view('pages.blog.post', compact('name', 'id'));
}
EDITIf you need to return it as JSON you can simply do:
编辑如果您需要将其作为 JSON 返回,您可以简单地执行以下操作:
public function post ($id, $name)
{
return view('pages.blog.post', ['json' => json_encode(compact('name', 'id'))]);
}
回答by Bojan Kogoj
Would something like this work?
这样的东西会起作用吗?
class BlogController extends Controller
{
//
public function post ($id, $name) {
//get id and name and pass it to the view
return view('pages.blog.post', ['name' => $name, 'id' => $id]);
}
}