Except for a URI and closure, a basic Laravel route is empty.

Route::get(‘/route’,function(){
Return “Something”;
})

Routes for the web interface are defined in web.php

And API routes are defined in routes/api.php, which are stateless and allocated to the API middleware group.

Available Router Method:

There are many router methods available

  1. Get
  2. Post
  3. Put
  4. Patch
  5. Delete
  6. Options
  7. Any
  8. Redirect 

Note: We should examine the incoming request using any, match, and redirect methods to see whether it matches the requested method when several methods use the same called “URI” and routes utilizing the get, post, put, patch, delete, and options methods.

CSRF Protection:

If you utilize html forms to Post, Put, Patch, or Delete, you must need a csrf token. Otherwise, the request will be denied.

<form method=”Post” action=”/pro”>
            @csrf
</form

 

Route Parameters:

In route, we can use or pass parameters.

Route::get(‘/profile/{id}’,function(){

Return $id;

})

 

Optional Route Parameters:

When parameters are optional, we must use a “?” after them.

Route::get(‘/profile/{id?}’,function(){
            If(issset($id))
            return $id;
            else
            return “Nothing”;

})

 

Route Groups:

Route groups, such as middleware, can be used to share route attributes.

1.All routes in a group should be assigned middleware.

Route::middleware('first','second')->group(function(){
    Route::get('/', function () {
        // Uses first & second middleware...
    });

    Route::get('/user/profile', function () {
        // Uses first & second middleware...
    });
});

 

2.We can also use SubDomain Routing using route groups

 

Route::domain('www.bangla.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});

 

3.Route Prefixes

 Route::prefix('admin')->group(function () {
    Route::get('/users', function () {
        // Matches The "/admin/users" URL
    });
});

 

4.Named Route

Route::name('admin.')->group(function () {
    Route::get('/users', function () {
        // Matches The "/admin/users" URL
        return 'hello';
    });
});

 

It just adds the administrator to all associated groups Route. We can retrieve the names of route groups by doing the following. 127.0.0.1:8000/users

Fallback Route:

If no other routes match, it will be executed.

Route::fallback(function () {
    //
});

 Rate Limiting:

We can limit requests depending on minutes or hours. Typically, this should be done within configureRateLimiting method.

App\Providers\RouteServiceProvider class.

RateLimiter::for('global', function (Request $request) {
    return Limit::perMinute(1000);
});

 

Using Throttle:

We can also use throttle to limit the rate.

Route::get('/', function () {
return view('login');
})->middleware('throttle:5,1');

 

Form Method:

Put, patch, and delete are not supported by HTML forms. As a result, we must utilize a hidden field to convey the put, patch, and remove commands.

<form action="/example" method="POST">

<input type="hidden" name="_method" value="PUT">

<input type="hidden" name="_token" value="{{ csrf_token() }}">

</form>

 

Additionally, the @method Blade directive may be used to create the _method input field:

<form action="/example" method="POST">

@method('PUT')

@csrf

</form>

 

Route Model Binding:

Model Binding is the process of injecting a model instead of an ID to retrieve information from a database.

Implicit Binding:

Here, we’re getting the user’s email by injecting a Model rather than an id.

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

 

Model binding in Controller method :

We can also do this with a controller.

Route::get('/users/{user}', [CommentController::class,'index']);

public function index(User $user)
{
//
return $user->email;
}

 

Customizing the key :

We can also resolve an eloquent model by using a different column name rather than the id.

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

 

We can also specify which field in the Model will be used to retrieve information from the database.

class User extends Authenticatable
{

public function getRouteKeyName()
{
return 'email'; // TODO: Change the autogenerated stub
}

}

So in that case Laravel will automatically use email instead of id.

Custom Key & Scoping:

Assume we want our second model to be a child of the first. For scope binding, we must tell Laravel which key will be used for children Mode.

Route::get('/users/{user}/posts/{post:user_id}', function (User $user, Post $post) {
return $post->details;
});

If we do not want to inform the Laravel children model key, we may accomplish so as follows.

Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
return $post->details;
})->scopeBindings();

We also can use scopeBindings in a group route.

Route::scopeBindings()->group(function () {
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
return $post->details;
});
});

 

Explicit Binding:

Customizing the resolution logic for explicit binding.

In RouteServiceProvider we can bind Model as per our requirement

Route::bind('user',function ($val)
{
return User::where('email',$val)->firstOrFail();
});

 

And in routez:

Route::get('/users/{user}', function (User $user) {
return $user->email;
});
URL : 127.0.0.1:8000/users/navids92@gmail.com

Result: navids92@gmail.com

 

By Navid Anjum

Full-stack web developer and founder of Laravelaura. He makes his tutorials as simple as humanly possible and focuses on getting the students to the point where they can build projects independently. https://github.com/NavidAnjum

2 thoughts on “How to use route in laravel 8”

Leave a Reply

Your email address will not be published. Required fields are marked *