Home » Php » Passing parameter to controller from route in laravel

Passing parameter to controller from route in laravel

Posted by: admin November 29, 2017 Leave a comment

Questions:

THIS IS A QUESTION FOR LARAVEL 3

Given the following route

Route::get('groups/(:any)', array('as' => 'group', 'uses' => '[email protected]'));

And the URL I would like to use,

http://www.example.com/groups/1

I would like to be able to use the (:any) value in my controller.

My controller looks like

class Groups_Controller extends Base_Controller {

    public $restful = true;    

    public function get_show($groupID) {
        return 'I am group id ' . $groupID;
    }  


}

How is this possible to do? I have tried a few things including the following

Route::get('groups/(:any)', array('as' => 'group', 'uses' => '[email protected]((:1))'));

but it did not work.

UPDATE

Anytime I try to pass in the arguments as show above i get a 404 error.

Thanks for the help!

Answers:

You don’t need anything special for adding paramaters. Just like you had it.

Route::get('groups/(:any)', array('as' => 'group', 'uses' => '[email protected]'));


class Groups_Controller extends Base_Controller {

    public $restful = true;    

    public function get_show($groupID) {
        return 'I am group id ' . $groupID;
    }  


}

Questions:
Answers:

This is what you need in 1 line of code.

Route::get('/groups/{groupId}', '[email protected]');

Suggestion: Use CamelCase as opposed to underscores, try & follow PSR-* guidelines.
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md

Hope it helps.

Questions:
Answers:

You can add them like this

  Route::get('company/{name}', '[email protected]');

Questions:
Answers:
    $ php artisan route:list
  +--------+--------------------------------+----------------------------+--    -----------------+----------------------------------------------------+---------  ---+
  | Domain | Method                         | URI                        |  Name              | Action                                             |    Middleware |
  +--------+--------------------------------+----------------------------+-------------------+----------------------------------------------------+------------+
  |        | GET|HEAD                       | /                          |                           
  |        | GET                            | campaign/showtakeup/{id}   | showtakeup         | App\Http\Controllers\[email protected] | auth       |     |

routes.php

  Route::get('campaign/showtakeup/{id}', ['uses' =>'[email protected]'])->name('showtakeup');

campaign.showtakeup.blade.php

 @foreach($campaign as $campaigns)


   //route parameters; you may pass them as the second argument to the method:

   <a href="{{route('showtakeup', ['id' => $campaigns->id])}}">{{ $campaigns->name }}</a>




            @endforeach

Hope this solves your problem.
Thanks