Ad

Passing Request Parameter To View - Laravel

- 1 answer

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}', '[email protected]')->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');
    }
}
Ad

Answer

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'))]);
}
Ad
source: stackoverflow.com
Ad