5

I have this route:

Route::get('/MyModel/{id}', 'MyController@show');

The method show() accepts a parameter called id and I want to setup an alias for /MyModel/1 so it's accesible from /MyCustomURL.

I already tried a few combinations, like:

Route::get('/MyCustomURL', ['uses' => 'MyController@show', 'id' => 1]);

But I keep getting missing required argument error for method show().

Is there a clean way to achieve this in Laravel?

Camilo
  • 6,504
  • 4
  • 39
  • 60
  • 1
    I recently discovered another way of setting up the routes, without annoying "@". `Route::get('my-model/{id}', [MyController::class, 'show'])->name('show');` it gives an option to my IDE to click-open MyController class from the router file. – Yevgeniy Afanasyev Jan 20 '20 at 02:57

4 Answers4

8

In Laravel 5.4 (or maybe earlier) you can use defaults function in your routes file.

Here is example:

Route::get('/alias', 'MyController@show')->defaults('id', 1);

In this case you don't need to add additional method in your controller.

Scofield
  • 4,195
  • 2
  • 27
  • 31
  • It seems like this has been in Laravel since version 4.1. I'll try it out and if it works, I'll switch to this answer! Thanks. – Camilo Oct 02 '17 at 14:26
1

In same controller (in your case MyController ?) you should create one new method:

public function showAliased()
{
   return $this->show(1);
}

and now you can define your aliased route like so:

Route::get('/MyCustomURL', 'MyController@showAliased');
Camilo
  • 6,504
  • 4
  • 39
  • 60
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • The only thing I don't like about this approach it's that I must setup a method for each alias. But it actually answers the question. Thanks. – Camilo Jun 15 '16 at 19:22
1

define your route like this: you can use "as" to give your route any name that you need.

Route::get('/MyModel/{id}' , [
        'as'=>'Camilo.model.show',
        'uses' => 'MyController@show' ,
    ]) ;

now if you want to access this route, you can generate url for it, based on its name like this:

route('Camilo.model.show', ['id' =>1]) ;
Camilo
  • 6,504
  • 4
  • 39
  • 60
Salar
  • 5,305
  • 7
  • 50
  • 78
  • 1
    I don't think this is what I'm looking for. This is simple redirecting to `/MyModel/1` and not an alias. – Camilo Jun 15 '16 at 19:19
-1
Route::get('MyModel/{id}', 'MyController@show');

not

Route::get('/MyModel/{id}', 'MyController@show');

Good Luck!

Camilo
  • 6,504
  • 4
  • 39
  • 60
hfekher
  • 668
  • 4
  • 14
  • Thanks for the tip but what's the difference between having the backslash or not at the beginning of the route? – Camilo Jun 15 '16 at 19:20
  • if that helped you , please accept the answer , for your question ; the diffirent is that thr first route is : localhost/yourproject/public/MyModel/5 for the second the route is : localhost/yourproject/public//MyModel/5 that's why your controller can't reat your id variable. – hfekher Jun 15 '16 at 19:34