skip to Main Content

route by {id} for example /author/{id} isn’t problem form me but i want to have route by {name} for example /author/{name}

i have code idea but i get 404 not found error:

php 8.2
laravel 10
code:

Route

Route::get('/authors/{authorname}', [AuthorController::class, 'showByName'])->name('authors.showbyname');

Controller

public function showbyname(author $authorsname)
{
    $authors = author::with(['book.personaldata'])->get();

    return view('authors.show',  compact('authorname', 'authors' ));

}

//
<-a href="{{ url(‘/author/’ . urlencode($author->name)) }}"->

("-"added on purpose because the link was disappearing)

https://laravel.com/docs/10.x/urls#urls-for-named-routes
https://laravel.com/docs/10.x/routing#parameters-regular-expression-constraints

2

Answers


  1. Route:

    Route::get('/authors/{name}', [NameController::class, 'nameDetail']);
    

    Controller

    use AppModelsName;
    use IlluminateHttpResponse;
    
    public function nameDetail($name)
    {
        $detail = Name::where('name', $name)->get();
    
        return response(['success' => $detail], 200);
    
    }
    
    Login or Signup to reply.
  2. Route

    Route::get('/authors/{authorname}', [AuthorController::class, 'showByName'])->name('authors.showbyname');
    

    Controller

    public function showByName($authorname)
    {
        $author = Author::with(['book.personaldata'])->where('name', $authorname)->firstOrFail();
        return view('authors.show', compact('author'));
    }
    

    Link

    <a href="{{ route('authors.showbyname',$author->name) }}">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search