moh_abk
moh_abk

Reputation: 2164

Passing request parameter to View - Laravel

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

Upvotes: 4

Views: 16370

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111859

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

Upvotes: 2

Bojan Kogoj
Bojan Kogoj

Reputation: 5649

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

Upvotes: 2

Related Questions