Tự học Laravel: (24) NAMED ROUTE

So far, when specifying a URL in a controller or view, we have written the path directly to the source code. However, with this method, when there is a change in the path, many points have to be changed. Therefore, I would like to solve this problem by naming the root and specifying the URL as the root name.

NAMED ROUTE CONFIGURATION

Modify routes/web.php to name the routes.

//app/Http/routes.php
 
...
Route::get('/', 'WelcomeController@index')->name('home');
Route::get('contact', 'PagesController@contact')->name('contact');
Route::get('about', 'PagesController@about')->name('about');
 
Route::get('articles', 'ArticlesController@index')->name('articles.index');
Route::get('articles/create', 'ArticlesController@create')->name('articles.create');
Route::get('articles/{id}', 'ArticlesController@show')->name('articles.show');
Route::post('articles', 'ArticlesController@store')->name('articles.store');
Route::get('articles/{id}/edit', 'ArticlesController@edit')->name('articles.edit');
Route::patch('articles/{id}', 'ArticlesController@update')->name('articles.update');
Route::delete('articles/{id}', 'ArticlesController@destroy')->name('articles.destroy');

We added a name() method at the end of the line to name each route.

HOW TO USE NAMED ROUTES

CONTROLLER

// app/Http/Controllers/ArticlesController.php
    ...
    ...
    public function store(ArticleRequest $request) {
        ... 
        //return redirect('articles')
        return redirect()->route('articles.index')
            ->with('message', 'Save Ok');
    }
    ...
    ...
    public function update($id, ArticleRequest $request) {
        ... 
        //return redirect(url('articles', [$article->id]))
        return redirect()->route('articles.show', [$article->id])
            ->with('message', 'Update ok');
    }

I changed the route specified by redirect directly to named route using the route() method.

VIEW

//resources/views/articles/create.blade.php
 
@extends('layout')
 
@section('content')
    <h1>Write a New Article</h1>
 
    <hr/>
 
    @include('errors.form_errors')
 
 
    {{-- Form::open(['url' => 'articles']) --}}
    {!! Form::open(['route' => 'articles.store']) !!}
        @include('articles.form', ['published_at' => date('Y-m-d'), 'submitButton' => 'Add Article'])
    {!! Form::close() !!}
 
@endsection

I changed the URL path written by Form::open to named route.

EXERCISE

Please try to change everything that specifies the URL in the controller or view to the specified in the named route.

https://laravel.com/docs/master/routing#named-routes
https://laravelcollective.com/docs/master/html#opening-a-form

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.