laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

[Proposal] Helper function to get a route name of the previous request. #1392

Open avosalmon opened 5 years ago

avosalmon commented 5 years ago

I needed to render the different HTML depending on which page the user come from. So I implemented a helper function like this,

if (! function_exists('previous_route')) {
    /**
     * Generate a route name for the previous request.
     *
     * @return string|null
     */
    function previous_route()
    {
        $previousRequest = app('request')->create(app('url')->previous());

        try {
            $routeName = app('router')->getRoutes()->match($previousRequest)->getName();
        } catch (NotFoundHttpException $exception) {
            return null;
        }

        return $routeName;
    }
}

Then I used the helper in my blade.

@if (previous_route() === 'cart.items')
    {{-- some html content --}}
@endif

If many people encounter such a situation, I'm thinking of sending a PR to the laravel framework. What do you think?

powelski commented 5 years ago

To be honest, finding previous routes doesn't seem like the greatest idea to me. If you want to display different page depending on previous location, most likely you are about to implement some web anti-pattern. Remember that one crucial element of web experience is being able to refresh the page and link to it. Previous location is not only unreliable, but also shouldn't affect your current content. You should use session for this and store necessary data there.

Can you tell what are you planning to do? What is your app and what functionality are you building?

avosalmon commented 5 years ago

@powelski Thank you for your comment, my use case is like this. I have a login/registration page in my e-commerce application and there are multiple ways to get to the login page. In the shopping cart, if a user tried to go to the shipping/payment page but not logged in, he/she will be redirected to the login page. In this case, I want to display a checkout steps image in the login page which should not be displayed by default. So I display the image if users come to the login page from the cart.

@if (previous_route() === 'cart.items')
    <img src="image.png" >
@endif

Should I achieve this functionality using session?

powelski commented 5 years ago

I think you should use different URL for this page. It's easy in Laravel to have a small change in a view displayed by different URL.

abdessamadely commented 4 years ago

Thank you Just needed it, now