Reputation: 2228
I have to redirect to a particular Controller
based on URL
.
My URL is,
http://localhost/project/public/category-1?tracker=category
If the query string tracker
is category
, then it should redirect to ProductsController@category
route.
I have tried using the below code. But it doesn't work.
Route::any('{name}', function () {
if (Request::get("tracker") == "category")
Route::get('{name}', 'ProductsController@category');
});
But the below code works when not using Route
inside if statement
Route::any('{name}', function () {
if (AppHelper::decryptURL(Request::get("tracker")) == "category")
return 1;
});
The above code displays 1
in webpage, but when using Route::get('{name}', 'ProductsController@category')
instead return 1
it reutn blank page.
How to fix it. Is any problem in my coding.
Upvotes: 0
Views: 60
Reputation: 5623
That's the right example to take advantage of middleware which allows to hooks some functionality before the request reach the controller and the response been sent to the browser.
namespace App\Http\Middleware;
use Closure;
class CheckTarget
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->tracker <= "category") {
return redirect('name_of_your_route');
}
return $next($request);
}
}
Afther what you must register the new Middleware in Within App\Http\Kernel
Class like this
protected $routeMiddleware = [
\\...
'target' => auth' => \App\Http\Middleware\CheckTarget::class,
]
And to use use you'll do like this
Route::any('{name}', function () {
return view('your_view_file_name');
})
->middleware('target');
->name('any_name_you_want');
Route::any('{name}', function () {
if (Request::get("tracker") == "category") {
Route::get('{name}', 'ProductsController@category'); // Here you define another route instead of redirect
}
});
In your code there are one problem which is, instead of redirecting the user to the route which you want you are defining another Route
inside of another route handle which is uncommon, and should be avoid. To redirect you should use redirect
helper which take a URL to which Laravel will redirect
Upvotes: 1
Reputation: 4813
You may use
Route::any('{name}', function () {
$tracker = $request->query('tracker');
if($tracker === 'category') {
return (new \App\Http\Controllers\ProductsController())->category();
}
});
Or via dependency injection
Route::any('{name}', function (ProductsController $productsCtrl) {
$tracker = $request->query('tracker');
if($tracker === 'category') {
return $productsCtrl->category();
}
});
Upvotes: 1