3x071c
3x071c

Reputation: 1016

Laravel modify route parameter to name column instead of id

In my web.php file, I specify the following route:

Route::get('/{project}', 'ProjectsController@index');

In my ProjectsController, I define the public function index as follows:

use App\Project;
// ... Here is the class declaration etc.
public function index(Project $project) {
  dd($project->name);
}

Currently, I have one entry in my projects table, which I can call without any problems over my eloquent model. This is my entry:

Name: sampleproject
Description: This is a test.
ID: 1
// And the timestamps...

When calling /sampleproject, it returns a 404 error page.
[...]

UPDATE: When calling /1, which is the project id, everything works as expected. How can I modify my code so I can call my Controller over the project name, not the id?

Upvotes: 2

Views: 1292

Answers (2)

Haider Ali
Haider Ali

Reputation: 11

Just append your "project" parameter in the URL with ":name", so before appending your parameter is:

Route::get('/{project}', 'ProjectsController@index');

and after appending, your Route would look like this:

Route::get('/{project:name}', 'ProjectsController@index');

Upvotes: 1

in your model:

public function getRouteKeyName()
{
    return 'yourcolumn';
}

Upvotes: 6

Related Questions