Saturday , December 21 2024

How Routing Is Done In Laravel

What is Routing in Laravel?

Routing simply means mapping application URLs to application view files. They usually handle HTTP requests and server responses. Inside this article, we will see about followings –

So, step by step we will proceed and understand each Laravel 8 routing.

Basic Routing Configuration

As we have already discussed that all routes configuration of web applications we do in the web.php file. The file web.php you will find inside /routes folder

Let’s create a very basic route inside this –

//...

Route::get('about-us', function () {
  
    return 'Very basic route in application - Online Web Tutor Blog';
  
});

//...

How can we access it?

As we know we have two options available to access the application URL in the browser. These are the following ways.

  • php artisan serve
  • By application URL

Assuming application has been served by php artisan serve command. So to access the above route what we have defined above will be –

http://localhost:8000/about-us

This will simply print the static message that we have written inside the callback function of the closure route.

Route with View file

We can call view file directly from web.php. No need to create any controller.

Method #1

//...

Route::get('our-products', function () {
  
    return view("products"); // view file in /resources/views/products.blade.php
  
});

//...

Method #2

This is also termed view routes in Laravel.

//...

// Route::view('route-name', 'view-file')

Route::view('our-products', 'products'); 

// view file in /resources/views/products.blade.php

//...

So to access the above route what we have defined above will be –

http://localhost:8000/our-products

This will return products.blade.php view file content.

Route with Controller Method

In Laravel 8 routing, this is the most commonly used approach. This means we will have a route and routes map with the controller’s method and method points to a view file.

Open web.php file –

# Add these to headers
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SiteController;

//Route::get("/route-name", [SiteController::class, "method_name"]);

Route::get("services", [SiteController::class, "services"]);

Next, we need to create the controller. Controllers will be stored in the directory of /app/Http/Controllers. We create controllers in two different ways.

  • By PHP artisan command
  • A manual method of creating the controller

We will create a controller by artisan command.

$ php artisan make:controller SiteController
<?php

namespace App\Http\Controllers;

class SiteController extends Controller
{
    public function services()
    {
        return view("services");
    }
}

So to access the above route what we have defined above will be –

http://localhost:8000/services

This will return services.blade.php view file content.

Sending Parameters to Route

This route will send some parameter values to its associated method. Open up the web.php file –

# Add these to headers
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SiteController;

// Passing parameter to URL
Route::get("services/{service_id}", [SiteController::class, "services"]);

// Passing parameter to URL
Route::get('product/{id}', function ($id) {
    return 'Product ID '.$id;
});

// Passing values to view routes
Route::view('/about-us', 'about-us', ['name' => 'Muhammad Umer Farooq']);

So to access the above route what we have defined above will be –

http://localhost:8000/services/101

This will pass the 101 value to controller method services. Back to the controller and access this value.

SiteController.php

<?php

namespace App\Http\Controllers;

class SiteController extends Controller
{
    public function services($service_id)
    {
        //return "This is service we are using as an ID of ".$service_id;
      
        return view("services", ["id" => $service_id]);
    }
}

One more thing, this parameter is the required value for the route which we pass into the URL. If we don’t pass then it will give an error about missing parameters. In some cases, we need to pass parameters but as an optional value. This means we want to create optional parameters. So for that,

web.php

//...
Route::get('product/{id?}', function ($id = null) {
    return "Product: ". $id;
});
//...

In this case, we can either pass value or not It is optional now.

Routing with Regular Expression

n routes configuration, regular express set the value patter for parameters. From the above discussion, we understood passing parameter values to routes.

Now, in case we set the placeholder to accept some pattern values like – web.php

Route::get('product/{name}', function ($name) {
  
    return "Product Name: ". $name;
  
})->where('name', '[A-Za-z]+');

Here, {name} is required parameter. and by using where to placeholder “name” as you can see we have set a pattern for it. Inside {name} we can pass the values either in between A-Z or a-z. This means string value will be accepted only. If we send any integer, it will give an error.

To pass integer value –

Route::get('student/{id}', function ($id) {
  
    return "Student ID: ". $id;
  
})->where('id', '[0-9]+');

Passing two parameters in route.

Route::get('student/{id}/{name}', function ($id, $name) {
  
    return "Student name: ".$name." and ID : ".$id;
  
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Here, we have configured some routes in web.php

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get('about-us', function () {
    return 'Very basic route in application - Online Web Tutor Blog';
});

Route::get('our-products', function () {
    return view("products"); // view file in /resources/views/products.blade.php
});

Route::get('product/{id}', function ($id) {
    return 'Product ID '.$id;
});

To check all available routes in the Laravel application, we have an artisan command to list all. Artisan command to check all routes –

$ php artisan route:list

Routing List

Redirect Routes

If we want to redirect some URLs and/or routes to some different URL, we can use the concept of redirect routes. By default, Route::redirect returns a 302 status code. But if we want to change we can pass into its syntax.

// When we open http://localhost:8000/source-url then it will be redirected to 
// http://localhost:8000/desitnation-url

Route::redirect('/source-url', '/desitnation-url');

//Route::redirect('/source-url', '/desitnation-url', 301);

Routing Methods

The router in Laravel 8 allows us to register routes that respond to any HTTP request as –

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

According to the request type, we can move further with the Route method. To learn more about routing in Laravel 8, you can see the available document here on the official website.

We hope this article helped you to learn Laravel 8 Routing in a very detailed way.

Check Also

Many To Many Relation – Eloquent

Many To Many Relation Today our leading topic is many-to-many relationship Laravel 9. I would …