One route controller 2 - Laravel

I have a term based route, I need to call the appropriate controller. eg,

Route::get('/{term}','Usercontroller')
Route::get('/{term}','brandcontroller')

      

I want to achieve something similar. what takes place is a name (string), based on that row, it either belongs to the user table or the brands table. how can I achieve something like this with Service Container. that before deciding which route to take based on the term, if it belongs to the USER class, the custom controller should be called, or if it belongs to the brand class, the brand controller route should be used. Any help would be appreciated. Thanks to

+3


source to share


1 answer


Create IsBrand middleware and check if the brand exists?

Route::group(['middleware' => 'IsBrand'], function () {
    Route::get('{term}', 'BrandController');
});

      

The same goes for IsUser.

Route::group(['middleware' => 'IsUser'], function () {
    Route::get('{term}', 'UserController');
});

      



Use php artisan make:middleware IsBrand

to create middleware.

This command will place the new IsBrand

class in your directory app/Http/Middleware

.

<?php

namespace App\Http\Middleware;

use Closure;

class IsBrand
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (App\Brand::where('brand_name', $term)->count())) {
            return $next($request);
        }
    }

}

      

+3


source







All Articles