Laravel routing

Laravel routes are used to bind url to controller action. When you create new pages in laravel you have to remember three things.

  • You first decide what would be the url that user will access via browser
  • How you can bind this url with a specific controller methods
  • Which view will be rendered by the controller method

When you are learning laravel framework the first thing you will do after installation is to define routes. Each route will bind url with a specific controller action. In this tutorial we will only learn about routing.

What is REST api routes?

Folllowings are some of the commonly used http methods: These methods basically corresponds to create, read, update and delete operations.

Route::get($uri, $callback); // Used to list records from the database
Route::post($uri, $callback); // Used to create a record in the database
Route::put($uri, $callback); // Used to update or replace record in database
Route::patch($uri, $callback); // Used to update or modify the records in DB 
Route::delete($uri, $callback); // Used to delete a record from the table

POST - commonly used method to create new record or resource. Form is submitted via POST method and data submitted via this method can not be seen via browser url. When record is created successfully it returns with 201 status code.

GET - commonly used method to read single or multiple records or resource. It is basically read only method. It does not modify any data.

PUT - commonly used method to update data or to create data in case client supply the id that needs to be updated.

PATCH - commonly used method to update partial data in the database rather then supplying all data for a single record.

DELETE - commonly used method to delete a record or resource

How to define route in laravel?

Routes in laravel are defined in following location:

  • routes/api.php    -> Routes for url prefixed with /api
  • routes/web.php   -> All web routes are defined here

Followings are some of the example of basic routes:

# Defines a route that lists all the users using GET method
Route::get('user', [UserController::class, 'show'])->name('');

# Defines a route that creates user using POST method
Route::post('user', [UserController::class, 'store'])->name('');

# Defines a route that update user partially using PATCH method
Route::patch('/user/:id', [UserController::class, 'update'])->name('user.update');

# Defines a route that deletes user using DELETE method
Route::delete('/user/:id', [UserController::class, 'delete'])->name('user.delete');

How to define a route without controller?

# Creates a login route with extension and returns view
Route::get('login', function() { 
   return view('auth.login'); 

# Route that returns view directly using GET method
Route::view('/dashboard', 'dashboard');

# Route post login
Route::post('login', function() {
    // Your logic to login

# Route that returns view by passing some variables to view
Route::view('/welcome', 'welcome', ['name' => 'Sandip Patel']);

How to define routes with parameters?

# Define a route where id should be numeric only
Route::get('/user/{id}', [UserController::class, 'show'])->where('id', '[0-9]+');

# Define a route where name should be alpha only
Route::get('/user/{name}', [UserController::class, 'getName'])->where('name', '[A-Za-z]+');

# Define a route where name should be alpha only and id should be numeric only
Route::get('/user/{id}/{name}', [UserController::class, 'get'])->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Routes with groups and middlewares

If you decided to group some routes that needs to have certain middlewares attached to them you can easily define them in laravel. Let say that your application has both front and backend.

Only logged in users are allowed to access some urls. You can define a middleware that checks to see if user is logged on or not and then group some routes so that they implement such middleware.

Let's check the following examples:

Route::middleware(['login'])->group(function () {
    Route::get('user', [UserController::class, 'get']);
    Route::get('user/:id', [UserController::class, 'show']);

Route::middleware(['web'])->group(function () {
    Route::get('login', [AuthController::class, 'login']);
    Route::get('logout', [AuthController::class, 'logout']);

Using many middleware

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second middleware...
    Route::get('/user/profile', function () {
        // Uses first & second middleware...

Define routes with prefix

Route::prefix('admin')->group(function() {
    Route::get('user', [UserController::class, 'get']);
    Route::get('users/:id', [UserController::class, 'show']);

How to get current route name or action or route?

# Get current route
$route = Route::current();

# get current route name
$name = Route::currentRouteName();

# get current route controller action
$action = Route::currentRouteAction();

How to define 404 route?

# Define not found route
Route::fallback([HomeController::class, 'notFound'])->name('notFound');  

# Define 404 route without controller
Route::fallback(function () {
    return view("404");

How to group routes based on sub-domain

Route::domain('{sub_domain}')->group(function () {
    Route::get('user/{id?}', function ($sub_domain, $id) {
        // Your logic handle

How to define route name

Route::get('/user/profile', function () {
    // Your logic handle

How to using a route name

// Redirect to a route name
return redirect()->route('profile');

// Using in link
<a href="{{ route('profile') }}">Go to profile</a>

Artisan command for Route

  • Show list route of application
php artisan route:list
  • Clear cache of route
php artisan route:clear
  • store route to cache
php artisan route:cache
Khôi Phạm
SUNTECH VIỆT NAM   Đăng ký để nhận thông báo mới nhất