Route not defined

This is my routes:

$app->group(['prefix' => 'book/'], function ($app) {
    $app->get('/','BooksController@index'); //get all the routes    
    $app->post('/','BooksController@store'); //store single route
    $app->get('/{id}/', 'BooksController@show'); //get single route
    $app->put('/{id}/','BooksController@update'); //update single route
    $app->delete('/{id}/','BooksController@destroy'); //delete single route
});

When I try to generate an URL, the system return that Route [book] not defined.

@foreach ($books as $book)
    <li>
        <a href="{{ route('book', ['id' => $book->id]) }}">
            {{ $book->name}}
        </a>
    </li>
@endforeach

What I miss?

2 answers

  • answered 2017-06-17 18:29 Anand Siddharth

    You didn't name the route

    $app->group(['prefix' => 'book/'], function ($app) {
    
       $app->get('/{id}/', [ 
          'as' => 'book', 
          'uses' => 'BooksController@show'
       ]);
    
    });
    

    And then you can do this

    @foreach ($books as $book)
    <li>
        <a href="{{ route('book', ['id' => $book->id]) }}">
            {{ $book->name}}
        </a>
    </li>
    @endforeach
    

  • answered 2017-06-17 18:29 utdev

    Try it this way, thus it's more readable:

    # Book routes
    Route::group(['prefix' => 'books'], function ()
    {
        Route::get('/', ['as' => 'index', 'uses' => 'BooksController@index']);
        Route::post('store', ['as' => 'store', 'uses' => 'BooksController@store']);
        Route::get('show/{id}', ['as' => 'show', 'uses' => 'BooksController@show']);
        Route::post('update/{id}', ['as' => 'update', 'uses' => 'BooksController@update']);
        Route::delete('destroy/{id}', ['as' => 'destroy', 'uses' => 'BooksController@destroy']);
    });
    

    I also think that you do not need the put method, you can use update + method spoofing in your form. For more information about method spoofing have a look at the docs