JeffH's avatar
Level 8

301 Redirect function

Is something like this possible? It doesn't seem to be working for me. What I am trying to do is use the id in the old path, get the item, and redirect it based on two pieces of data in the collection.

    Route::get(  '/news/{id}', function( $id ) { 
        $news= News::find( $id );
        return Redirect::to( '/news/' . $news->number . '/' . $news->issue, 301 ); 
    });

When i go to the url, i get a 404 error, instead of a redirect. Im not sure how to troubleshoot this problem.

0 likes
4 replies
rin4ik's avatar

save it into variable and die and dump the result.see if it is correct path. make sure you import News class as well

$variable = '/news/' . $news->number . '/' . $news->issue;
dd($variable);
2 likes
Cronix's avatar

Try return redirect( '/news/' . $news->number . '/' . $news->issue, 301); If you leave off the 301 it issues a 302 by default.

It would also be good to use findOrFail() instead of just find(). I imagine it would produce a 404 error if it can't find the $news, and then redirecting using properties that don't exist, so if the requested $id isn't found, it's proper to issue a 404 in that case, which findOrFail does if it doesn't find it.

1 like
Snapey's avatar

open your browser tools and switch to the network view

hit your route. Do you get 404 immediately, or a redirect a 301 and then a 404 ?

1 like
JeffH's avatar
Level 8

I must have been having a weird day because I don't recall doing anything differently but it works now. Thanks guys.

Please or to participate in this conversation.