Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vtxmg's avatar

Include common tasks like session.

Hello Everybody .. I want to know the suitable way to include common tasks like session in every controllers. I have been doing this using constructor but its really really repetitive. Here's my code.

use Illuminate\Session\Store as Session;

class MyController extends Controller {
    protected $session;
protected $data;

    /**
     * @param Session $session
     */
    public function __construct(Session $session){
        $this->session = $session;

        $session->has('info')?$this->data['info'] = $session->pull('info'):'';
        $session->has('task')?$this->data['task'] = $session->pull('task'):'';
    }

These sessions are required for every controllers ..

0 likes
4 replies
mstnorris's avatar

Create a BaseController and extend that.

class BaseController extends Controller {
    // your generic Session code here
}

class MyController extends BaseController {
    // all your standard stuff here
}
1 like
bobbybouwmann's avatar

What you do is create a BaseController like this

class BaseController extends Controller {
    
    public function __construct(Session $session) {
        $this->session = $session;

        $session->has('info')?$this->data['info'] = $session->pull('info'):'';
        $session->has('task')?$this->data['task'] = $session->pull('task'):'';
    }

}

Now you extend all your controllers that use the session with that BaseController

One question though, why do you need the sessions? There might be a better way to solve this ;)

1 like
vtxmg's avatar

@bobbybouwmann I need these for displaying messages to users... n I would like to hear the better way for this?

bobbybouwmann's avatar

The better way would be this, so let the response or the redirect handle the sessions

return redirect()->route('whatever')->with('info', 'Test Message')->with('task', 'Task');

Please or to participate in this conversation.