将请求参数传递给 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:54:13  来源:igfitidea点击:

Passing request parameter to View - Laravel

phplaravellaravel-5blade

提问by moh_abk

Is it possible to pass a routeparameter 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]);
    }
}