Passing request parameter to View - Laravel

依然范特西╮ 提交于 2019-12-10 17:57:14

问题


Is it possible to pass a route parameter to a controller to then pass to a view in 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

class BlogController extends Controller
{
    //
     public function post () {

     //get id and name and pass it to the view

        return view('pages.blog.post');
    }
}

回答1:


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'));
}

EDIT If you need to return it as JSON you can simply do:

public function post ($id, $name) 
{
   return view('pages.blog.post', ['json' => json_encode(compact('name', 'id'))]);
}



回答2:


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]);
    }
}


来源:https://stackoverflow.com/questions/34483859/passing-request-parameter-to-view-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!