Best Practice for HTTP Redirect

Published 1 year ago by Tipoff

I'm reading the documentation on redirects (https://laravel.com/docs/5.4/redirects), but having some trouble setting one up the way I want. I have a quotes database table with an id column that begins incrementing at 1,000,000 so there will always be 7 digit id numbers for them. I want people to visit mywebsite.com/1000000 and be redirected to mywebsite.com/quotes/quotations/1000000 and have tried the following to no avail:

Route::get('quotes/quotations/{quote}', '[email protected]');

Route::get('{quote}', function () {
    return redirect()->action(
    '[email protected]', ['id' => {quote}]
);

I have also tried things like:

Route::get('quotes/quotations/{quote}', '[email protected]');

Route::get('{quote}', function () {
    return redirect('quotes/quotations/{quote}');
});

My main route works, but both attempts at the redirect are failing. I think it is not passing along the prior {quote} id value, but I can't find an example with this to fix it. Any help and advice on the best practice for implementing this would be appreciated. Thanks

Best Answer (As Selected By Tipoff)
martinbean

@DrewRoberts I’d set up a regular expression pattern for the quote parameter. You’ll can then pass it along like this:

Route::get('quotes/{quote}', '[email protected]')->name('quote.show');

Route::get('{quote}', function ($id) {
    return redirect()->route('quote.show', $id);
})->where('quote', '[0-9]{7,}');
martinbean

@DrewRoberts I’d set up a regular expression pattern for the quote parameter. You’ll can then pass it along like this:

Route::get('quotes/{quote}', '[email protected]')->name('quote.show');

Route::get('{quote}', function ($id) {
    return redirect()->route('quote.show', $id);
})->where('quote', '[0-9]{7,}');
Tipoff
Tipoff
1 year ago (26,000 XP)

That's beautiful, @martinbean. It worked like a charm.

martinbean

@DrewRoberts Glad to have helped! :D

Tipoff
Tipoff
1 year ago (26,000 XP)

@martinbean, I'm making a change to my route structure:

Route::get('quotes/{quoteauthor}/{quote}', '[email protected]')->name('quote.show');

What changes do I need to make to the redirect route to have it pull the correct author for the quote and redirect it the appropriate URL?

Please sign in or create an account to participate in this conversation.