Laravel Routing


Laravel Routing – The Laravel Routing is used to defined route in your route files, which are located in route directory .


Laravel Routing.

Let us understand how to use laravel Routing.

Function:-

There are some followings function available in laravel Routing.

  • 1. Basic Routing.
  • 2. Route Parameters.
  • 3. Named Routes.
  • 4. Route Groups.
  • 5. Route Model Binding.
  • 6. Form Method Spoofing.
  • 7. Accessing The Current Route.

1. Basic Routing.

The most basic Laravel route simply accept a uri and a closure, providing a very simple and expressive method of defining routes.

Let’s look at a simple example.

<?php

Route::get('message', function () {
    return 'Welcome To Tutorialsplane.com';
});

Output will be like this:-

Laravel Routing

The default route files

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.

Available Router Methods

The router allows you to register routes that respond to any HTTP verb

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

Sometimes you may need to register a route that responds to multiple HTTP verbs. We can use match and any method to register a route that responds to all HTTP verbs.

Let's look at a simple example.

Route::match(['get', 'post'], '/', function () {
    return 'Hello World!';
});

Route::any('message', function () {
    return 'Hello World';
});
Laravel Routing

CSRF Protection

Any HTML forms pointing to POST, PUT or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected.

<form method="POST" action="/profile">
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
</form>

2. Route Parameters.

Required Parameters

Sometime you will need to capture segments of the URI within your route. For example, you may need to capture a user's ID from the URL. You may do so by defining route parameters.

Route::get('/parameter/{id}', function ($id) 
{
    return 'Parameter_id_'.$id;
});
Laravel Routing

We can define as many route parameters as required by your route.

Route path (web.php):-

Route::get('/posts/{postId}/comments/{commentId}', 'AccountController@posts');

Controller part (AccountController.php):-

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\TestModel;
use Illuminate\Support\Facades\Input;
class AccountController extends Controller
{
  public function posts($postId, $commentId)
   {
     return "Posts_id_$postId <br> Comments_id_$commentId";
   }
}
Laravel Routing

Optional Parameters

You may need to specify a route parameter, but make the presence of that route parameter optional. Make sure to give the route's corresponding variable a default value

route path:-

Route::get('user/{name?}', 'AccountController@OptionalParameter');

Controller part:-

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\TestModel;
use Illuminate\Support\Facades\Input;
class AccountController extends Controller
{
  public function OptionalParameter($name = 'Solid Coupon')
    {
	return "$name";
    }
}
Laravel Routing

Regular Expression Constraints

You may forcly the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be forcly.

route path:-

Route::get('expression/{id}/{name}', 'AccountController@RegularExpression')->where(['id' => '[0-9]+', 'name' => '[A-z]+']);

Controller part:-

public function RegularExpression($id, $name)
{
return "Id = $id <br> Name = $name";		
}
Laravel Routing

Global Constraints

If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern method. You should define these patterns in the boot method of your RouteServiceProvider.

public function boot()
{
    Route::pattern('id', '[0-9]+');
    parent::boot();
}

Once the pattern has been defined, then program will be executed when id is numeric.

3. Named Routes.

Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route by chaining the name method onto the route definition.

Route::get('example/profile', function () {
    echo "Hello User!";
})->name('profile');

You can also specify route names for controller action.

Route path:-

Route::get('abc/profile', 'AccountController@nameRoute')->name('pic');

Controller path:-

public function nameRoute()
{
  return "Hello World!";		
}

Generating URLs To Named Routes

Once you have assigned a name to a given route, you may use the route's name when generating URL or redirects via the global route function.

$url = route('profile');
return redirect()->route('profile');

If the named route defines parameters, you may pass the parameters as the second argument to the route function. The given parameters will automatically be inserted into the URL in their correct positions.

Route::get('Admin/{id}/profile', function ($id) {
    $url = route('profile', ['id' => 1]);
	return "Print Always Same Result";
})->name('profile');
Laravel Routing

4. Route Groups.

Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group method.

Middleware

To assign middleware to all routes within a group, you may use the middleware key in the group attribute array. Middleware are executed in the order they are listed in the array.

Route::group(['middleware' => 'auth'], function () {
    Route::get('/', function ()    {
        // Uses Auth Middleware
    });

    Route::get('abc1/profile', function () {
		echo "Hii";
        // Uses Auth Middleware
    });
});

Namespaces

Another common use-case for route groups is assigning the same PHP namespace to a group of controllers using the namespace parameter in the group array.

Route::group(['namespace' => 'Admin'], function () {
    // Controllers Within The "App\Http\Controllers\Admin" Namespace
});

Sub-Domain Routing

Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the domain key on the group attribute array.

Route::group(['domain' => '{account}.myapp.com'], function () {
    Route::get('aa/{id}', function ($account, $id) {
        //
    });
});

Route Prefixes

The prefix group attribute may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with admin.

Route::group(['prefix' => 'route'], function () {
    Route::get('users', function ()    {
        return "Welcome";
    });
});
Laravel Routing

5. Route Model Binding.

When injecting a model ID to a route or controller action, you will often query to retrieve the model that corresponds to that ID. Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user's ID, you can inject the entire user model instance that matches the given ID.

Implicit Binding

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.

Route::get('api/users/{user}', function (App\User $user) {
    return $user->email;
});

Customizing The Key Name

If you would like model binding to use a database column other than id when retrieving a given model class, you may override the getRouteKeyName method on the Eloquent model.

public function getRouteKeyName()
{
    return 'slug';
}

Explicit Binding

To register an explicit binding, use the router's model method to specify the class for a given parameter. You should define your explicit model bindings in the boot method of the RouteServiceProvider class.

public function boot()
{
    parent::boot();

    Route::model('user', App\User::class);
}

Next, define a route that contains a {user} parameter.

Route::get('profile/{user}', function (App\User $user) {
    //
});

Customizing The Resolution Logic

If you want to use your own resolution logic, you may use the Route::bind method. The closure you pass to the bind method will receive the value of the URI segment and should return the instance of the class that should be injected into the route.

public function boot()
{
    parent::boot();

    Route::bind('user', function ($value) {
        return App\User::where('name', $value)->first();
    });
}

6. Form Method Spoofing.

HTML forms do not support PUT, Patch or Delete actions. So, when defining PUT, Patch or Delete routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method ield will be used as the HTTP request method.

<form action="/foo/bar" method="POST">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

You can use the method_field helper to generate the _method input.

{{ method_field('PUT') }}

7. Accessing The Current Route.

You can use the current, currentRouteName and currentRouteAction methods on the route facade to access information about the route handling the incoming request.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\TestModel;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Input;
class AccountController extends Controller
{
public function Route()
	{
		 echo $currentPath= Route::getFacadeRoot()->current()->uri();
		 echo "<br>";
		 echo $actionName = Route::getCurrentRoute()->getActionName();
		 echo "<br>";
		 echo $routeName = $abc = Route::currentRouteName();
	}
	
}

Refer to the API documentation for both the underlying class of the route facade and Route instance to review all accessible methods.

Output will be like this:-

Laravel Routing

Advertisements

Add Comment

📖 Read More