ホーム > Laravel > For Beginners How to specify name in Laravel routing
Laravel

For Beginners How to specify name in Laravel routing

Thank you for your continued support.
This article contains advertisements that help fund our operations.

I previously wrote an article on how to write Laravel routing.

In the above article, I summarized a writing style that almost eliminates problems if you remember and use it.

From there, I will write about how to add a name to the routing.

⇨ How to write Laravel routing

⇨ How to write routing that only logged-in users can use

⇨ How to write routing that specifies multiple middlewares

Why add a name

When creating a service, there are times when you want to change the URL.

For example, usability, ease of management, changing URL hierarchy, etc.

At such times, if you specify a name, the corresponding URL will be automatically changed just by modifying web.php.

Basic writing style

The basic code is as follows.

Route::get('/home', 'HomeController@index')->name('home');

This is the writing style with the specified name.

In the previous article, it was

Route::get('/home', 'HomeController@index');

I think that was it. Just add ->name('home') to it.

The part corresponding to home can be any text attached here, but it is written in accordance with the direction of the development site and naming conventions.

When creating layers with name,

->name('post.index')

Create layers using "." like this.

Basic way to call

route('home')
route('post.index')

You can call it with expressions like these.

In actual examples,

When specifying in an anchor tag link

<a href="{{ route('home') }}">Home</a>

For use in a form

<form methods="GET" action="{{ route('home') }}">

</form>

To be used in a Controller

  return redirect()->route('home');
  const home_url = route('home');

You can call it like this.

Occasionally misunderstood

In Laravel, when specifying layers in other functions, you can write the hierarchy "post/index" as "post.index".

However, with regard to the routing name, it is not allowed, and it will not work unless it matches completely.

For example, when name('post.index'),

×route('post/index')
○route('post.index')

It will be like this.

Summary

The above explains the method of specifying name in Laravel routing and the reason why it is better to specify routing.

For beginners, I think it's tough because there are many articles, but if you are unsure whether to specify a name or not, I think it's better to "specify".

If there are any corrections or other points, please let me know via DM on Twitter.

Thank you for reading until the end.

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!