Home > Back-end >  Are href="{{ url('articles') }}" and href="{{ route('articles') }
Are href="{{ url('articles') }}" and href="{{ route('articles') }

Time:03-23

I have this code

<a  href="{{ url('articles') }}">My articles</a>

it works fine, but I've seen in the documentation and other refs that we can use route instead of url():

<a  href="{{ route('articles') }}">My articles</a>

but it didn't work for me. what is the difference between them and why it didn't work for me? here is my route definition:

Route::resource('articles', ArticlesController::class); // generated by artisan command

CodePudding user response:

You'd want to call {{ route('articles.index') }} when using a resource route.

Actions Handled By Resource Controller has all the names for resource routes

Edit: depending on how you setup your routes they will not do the same:

{{ url('articles') }} calls the URL /articles.

If you have a named route defined as:

Route::get('/myarticles', [ArticleController::class, 'index'])->name('articles'); then {{ route('articles') }} will call the URL /myarticles.

Manual for Named Routes

CodePudding user response:

Both generate URLs under the hood. The difference being url generates it based on the provided path whereas route generates it based on the name of the route provided.

The reason your route has not worked is because there is no route named articles. Route::resource generates the routes for you, but the route you most likely want to reference is articles.index.

<a  href="{{ route('articles.index') }}">My articles</a>

You can use php artisan route:list to see all the available routes in your application.

  • Related