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...
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.
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?
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community