Passing request parameter to View - Laravel

13,929

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

Solution 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]);
    }
}
Share:
13,929
moh_abk
Author by

moh_abk

Updated on June 23, 2022

Comments

  • moh_abk
    moh_abk almost 2 years

    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');
        }
    }
    
  • moh_abk
    moh_abk over 8 years
    In my view I can view echo out the data this way {{$name}}. How can I pass this to JavaScript? Or apply json_encode to it
  • Marcin Nabiałek
    Marcin Nabiałek over 8 years
    You can simple pass it to JavaScript putting value for example <script>var = {{$name}}</script> or you can use <span id="name">{{$name}}</span> and using JavaScript get value of element with id='name'
  • moh_abk
    moh_abk over 8 years
    When I do var = {{$name}} I get an error thrown by my IDE expression expected.. Normally I would just do <?php echo $name ?> for example but I'm using blade which doesnt support such
  • Marcin Nabiałek
    Marcin Nabiałek over 8 years
    @moh.ABK Sorry of course it should be <script>var name = '{{$name}}'</script>