Skip to content

Instantly share code, notes, and snippets.

@jeffochoa jeffochoa/1.php Secret
Last active Jun 3, 2019

Embed
What would you like to do?
Redirect a request to a specific route in Laravel
<?php
Route::get(‘{category}/{slug}-{id}’, ‘ArticleController@show’)->name('article');
Route::get(‘{category}/{tag}’, ‘TagController@show’)->name('tag');
<?php
Route::macro(
'sendToRoute',
function (Request $request, string $routeName) {
$route = tap($this->routes->getByName($routeName))->bind($request);
$this->current = $route;
return $this->runRoute($request, $this->current);
}
);
<?php
class ArticleController
{
public function show(Request $request)
{
//...
// is not and article? then redirect
return \Route::sendToRoute($request, 'tag');
}
}
<?php
$request->category; // movies
$request->tag; // lord-of-the-rings-2
// Tag routes
http://localhost/movies/accion
http://localhost/movies/comedy
http://localhost/movies/kids
http://localhost/movies/lord-of-the-rings-2
// Article routes
http://localhost/movies/10-action-movies-for-the-weekend-123
http://localhost/movies/2020-upcoming-movies-124
http://localhost/movies/top-100-classic-movies-125
<?php
class ArticleController
{
public function show($category, $slug, $id)
{
$article = Article::find($id);
if (empty($article)) {
return app(\App\Http\Controllers\TagController::class)
->show($category, $slug.'-'.$id)
}
return view('article')->withArticle($article);
}
}
<?php
class TagController
{
public function show($category, $tag)
{
// do somehting
return view('tag');
}
}
<?php
class TagController {
public function show(Request $request) {
$tag = $request->tag;
$category = $request->category;
// do somehting
return view('tag');
}
}
<?php
// Route::get('{category}/{slug}-{id}');
// http://localhost/movies/lord-of-the-rings-2
$request->category; // movies
$request->slug; // lord-of-the-rings
$request->id // 2
<?php
class ArticleController
{
public function show(Request $request)
{
return app(\App\Http\Controllers\TagController::class)
->show($request)
// ...
}
}
class TagController
{
public function show(Request $request)
{
$request->category; // movies
$request->tag; // lord-of-the-rings
}
}
<?php
// In the ArticleController
return redirect()->route('tag', [
'category' => $request->category,
'tag' => $request->slug . '-' $request->id
]);
<?php
public function respondWithRoute($name)
{
$route = tap($this->routes->getByName($name))->bind($this->currentRequest);
return $this->runRoute($this->currentRequest, $route);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.