php - Laravel back() or redirect() does not work in Traits
Get the solution ↓↓↓I've been using Laravel helpers in all my Traits, assuming that helper functions work everywhere.
But while some functions likeabort()
work, I just realized thatreturn redirect()
andreturn back()
do not work!
Could some one please explain why?
After this, I'm a bit hesitant to trust Laravel... I mean what if next timeabort(403)
doesn't work some where (because I'm not aware of which function works where) and some one does things that they are not allowed to do!
Simplified Example:
namespace App\Http\Traits;
trait TestTrait{
public function doBack(){
return back();
}
public function doRedirect(){
return redirect()->route('test');
}
public function doAbort(){
abort(403);
}
}
use App\Http\Traits\TestTrait;
class TestController extends Controller{
use TestTrait;
public function testingBack(){
$this->doBack();
}
public function testingRedirect(){
$this->doRedirect();
}
public function testingAbort(){
$this->doAbort();
}
}
In the sample controller above,testingAbort()
method works buttestingRedirect()
andtestingBack()
do not! and they shows an empty page instead.
I'm assuming I have to do the redirects in the controller itself (instead of in Traits), but that would cause duplicating a lot of conditional code in controller methods, and I'm also not sure why this is happening.
Answer
Solution:
When you call a local method and expect the controller to act, you will need to return it, else the controller function will return null and not act on the trait return.
public function testingBack(){
return $this->doBack();
}
public function testingRedirect(){
return $this->doRedirect();
}
public function testingAbort(){
return $this->doAbort();
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key php
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.