Support the ongoing development of Laravel.io →
Eloquent Architecture

I am new to Laravel/OOP and am trying to reproduce a legacy site where there is a back button with very specific behavior. Basically, if you are coming from a new tab or a site that isn't ours, I want to take to back to the main News page, but otherwise it should take you back to the previous page.

this is from my blade template, which works fine:

@if(URL::previous() === Request::url())
/news/
@elseif (strpos(URL::previous(), URL::to('/')) === false)
/news/
@else 
{{ URL::previous() }}
@endif

But I figured I need to reuse it across a lot of pages, so I should try to write it as a helper function/something else more reuseable. When I try and create a new helpers class to use, I get this error- "Non-static method Illuminate\Routing\UrlGenerator::previous() should not be called statically, assuming $this from incompatible context" am I going about this completely incorrectly?

From my Helpers Class
class Helpers {

function BackLink(defaultbacklink $defaultbacklink)
{
    if (URL::previous() === Request::url()){
        return $defaultbacklink;
    } elseif (strpos(URL::previous(), URL::to('/')) === false) {
        return $defaultbacklink;
    } else {
        return URL::previous();
    }    
}

}

In my controller:
use App\Helpers;
use Illuminate\Routing\URLGenerator as URL;

    $foo = new Helpers;
    $backlink = $foo->BackLink('news');

I've also tried using Jeffrey Way's method to create custom helper functions (yes I ran a composer dump autoload) but it keeps saying "Call to undefined function App\Http\Controllers\setBackLink()" when it's actually in App\Http\helpers.php so lol...

Last updated 3 years ago.
0

You could also create a view partial. Then include that view wherever you need it.

In any case, regarding your question, you created a Helpers class. You need to then treat it like a class by having the proper namespace, importing it, etc.

0

I think I imported it correctly? at least the Helper class... seems like the error "Non-static method Illuminate\Routing\UrlGenerator::previous() should not be called statically, assuming $this from incompatible context" is from the way I handled the URL class, but I'm really not sure how to fix that front.

Maybe a view partial like you said would be easiest. :P Is it considered bad practice?

Last updated 9 years ago.
0

For this error: 'Non-static method Illuminate\Routing\UrlGenerator::previous()', it sounds like you are not correctly importing the URL facade.

You should be putting use URL; at the top.

0

I feel like an idiot now. Thanks!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

nchan0154 nchan0154 Joined 8 Oct 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.