Reputation: 35
I am new to laravel. I am defining this route to an edit button:
<a href="/editTasks/{{ $task->id }}"><button class="btn btn-primary">Edit task</button></a>
The url is generated fine but the page is not found. I am returning a view with my TaskController@edit
with this route:
Route::get('/editTasks/{{ $task->id }}', 'TaskController@edit');
Can someone help me out figuring what i am doing wrong?
Upvotes: 1
Views: 1750
Reputation: 4153
It's better to use "Route Model Binding". Your route should be like this:
Route::get('/editTasks/{task}', 'TaskController@edit');
And in Controller use something like this:
public function edit($task){
}
Upvotes: 0
Reputation: 3621
You need to use single {
instead of double, so it needs to be the following in your route:
Route::get('/editTasks/{taskId}', 'TaskController@edit');
And in your edit
function:
public function edit($taskId) { }
The double {
in the template is correct as this indicates to retrieve a variable
Extra information/recommendation:
It is recommended to let the variable name in the route match the variable in your function definition (as shown above), so you always get the expected variable in your function. If they do not match Laravel will use indexing to resolve the variable, i.e. if you have multiple variables in your route pattern and only use one variable in the function it will take your first route parameter even if you might want the second variable.
Example:
If you have a route with the pattern /something/{var1}/something/{var2}
and your function is public function test($variable2)
it would use var1
instead of var2
. So it it better to let these names match so you always get the expected value in your function.
Upvotes: 2
Reputation: 33186
When defining routes, the route parameters should only have one {
around them. Also, you should not use a variable in the declaration but a name for the variable.
In your example, this could be a valid declaration:
Route::get('/editTasks/{id}', 'TaskController@edit');
More information can be found in the docs: https://laravel.com/docs/5.7/routing#route-parameters
It is also recommended to use route names, so the url can be automatically generated.
For example:
// Route declaration
Route::get('/editTasks/{id}', 'TaskController@edit')->name('tasks.edit');
// In view
<a href="{{ route('tasks.edit', [$task->id]) }}">Edit task</a>
Upvotes: 6
Reputation: 3615
no you have to define in your route just like this :
Route::get('/editTasks/{id}', 'TaskController@edit');
you don't have $task in your route and you dont need to write any other thing in your route. in your controller you can access to this id like this :
public function edit($taskId) {
}
and only you do this
Upvotes: 2