-2

I have a base controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Auth;

class Controller extends BaseController
{
  use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

  public function __construct()
  {
    $user = Auth::user();
    if (!empty($user))
    {
      $uid = $user->id;
      DB::table("users")
        ->where("id", $uid)
        ->update(array(
          'last_time_page_accessed' => time(),
        ));
    }
  }
}

The problem is, even if I am logged in, it doesn't reach the $uid = $user->id part, because the $user object is always empty.

This is how I call it from the main controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Redirect;
use Auth;
use DB;
use App\Files;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;

class ChatController extends Controller
{

  public function __construct()
  {
    parent::__construct();
    $this->middleware('auth');
  }

}

What am i missing? Why can't it access it?

UPDATE

I tried switching these, and it also didn't work:

  public function __construct()
  {
    $this->middleware('auth');
    parent::__construct();
  }
rockstardev
  • 13,479
  • 39
  • 164
  • 296
  • `Auth::user()` it will work if your route is protected by `auth()` and it is base controller it means so many controller which is not protceted by `auth()` it will not work – Kamlesh Paul Oct 01 '20 at 06:07
  • 2
    The user is not available at the point where the controller is constructed. For what you're trying to do specifically you should use middleware – apokryfos Oct 01 '20 at 06:11

1 Answers1

1

As apokryfos pointed out, the authenticated user is not yet available when the controller is constructed, so auth()->user() will always be null.

What you're trying to do is a perfect use case for Middleware.

You can use something like this. If you want this code to run for every route, you may register your Middleware as global Middleware for every web route.

<?php   

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class StoreLastTimeUserAccessedPage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
       if ($user = Auth::user()) {
           $user->update([
               'last_time_page_accessed' => time()
           ]);
       }

       return $next($request);
    }
}
timgvandijk
  • 429
  • 2
  • 10