Search code examples
phplaravelrouteslaravel-7laravel-route

Route is not identified in Laravel route


I have been trying to learn laravel, but for some reason my routes are not identified specially in those cases where I need to pass route parameters like id. This is my web.php

Route::put('/todos/{$todo}/complete','TodoController@complete')->name('todos.complete');
Route::resource('/todos','TodoController');

This is from where I am calling this route

@foreach($todos as $todo)
    <li class="flex justify-between p2">
        @if($todo->completed)
            {{-- <p><del>{{$todo->title}}</del></p> --}}
            <p class="line-through">{{$todo->title}}</p>

        @else
        <p>{{$todo->title}}</p>
        @endif

        <div>
            <a href="{{route('todos.edit',[$todo->id])}}" class="btn btn-primary"><i class="fa fa-edit"></i></a>
            @if(!$todo->completed)      
        <span onclick="event.preventDefault();document.getElementById('form-complete-{{$todo->id}}').submit()" class="btn btn-danger fa fa-check px2" ></span>
        <form action="{{route('todos.complete',$todo->id)}}" id="{{'form-complete-'.$todo->id}}" method="post" style="display:none">
                @csrf
                @method('put')
               
            </form>
            @else
            <span onclick="event.preventDefault();" class="btn btn-success fa fa-check px2" ></span>
            <form action="{{route('todos.complete',$todo->id)}}" method="post" style="display:none">
                @csrf
                @method('put')

            </form>

            @endif
     
        </div>
        
    </li>   
           
    @endforeach

I have setup my controller as follows:

public function complete(Todo $todo){
    $todo->update(['completed'=>true]);
    return redirect()->back()->with('message','Todo Completed');
}

This is my route for this :

| PUT       | todos/{$todo}/complete | todos.complete | App\Http\Controllers\TodoController@complete | web 

I had this similar issue in post route for edit where I needed to pass parameter as well. There I simply solved using a resource method. But in this case since I had to input a custom function in controller, the route is not available. I am having a 404 not found error in:

http://127.0.0.1:8000/todos/1/complete

It has been a while since I did laravel. So I am new the basics of routing. Please help me out


Solution

  • Try changing:

    Route::put('/todos/{$todo}/complete','TodoController@complete')->name('todos.complete');
    

    to:

    Route::put('/todos/{todo}/complete','TodoController@complete')->name('todos.complete');
    

    Without the $ of {$todo}

    See: Route Parameters