StuBlackett
StuBlackett

Reputation: 3857

Sharing a variable in controller - Laravel

I'm getting the user_id from the session and using it quite a bit throughout my contrpller. So am looking at ways of retrieving that variable.

I have set everything up to get it (How I understand) but the Variable is returning

null

My Controller looks as follows :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\VideoLog;

class VideoController extends Controller
{
    private $user_id;

    public function __construct(Request $request)
    {
        $user_id = session('id');
        $this->user_id = $user_id;
    }

    public function log_watched(Request $request)
    {
        dd($this->user_id);

        // See If Video Has Been Watched Before....
        $video_watched = VideoLog::where('user_id', $this->user_id);
    }
}

Is it something to do with the session?

How would I retrieve it?

Upvotes: 0

Views: 1552

Answers (1)

Rwd
Rwd

Reputation: 35190

The reason you're having this issue is because the controller __construct method is run before the middleware that starts the session.

(more information here)

As the post says, you can get round this issue by using the middleware method in the controller's __construct method:

public function __construct()
{
    $this->middleware(function ($request, $next) {

        $this->user_id = session('id');

        return $next($request);
    });

}

This will allow you to set the user_id on the controller.

Upvotes: 4

Related Questions