-1

I have DashboardController where I need to fetch dashboard data based on a field site from users table for the logged in user.

This is my controller:

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DashboardContoller extends Controller {
    protected $today;
    protected $site;

    public function __construct() {
        $this->middleware('auth');
        $this->today = date("Y-m-d");
        $this->site = auth()->user()->site; // this line is showing error
    }

    // Rest of my code goes here
}

It is giving me "Trying to get property 'site' of non-object" error when I try to access the field site. What am I doing wrong?

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Aditya Amit
  • 71
  • 2
  • 9
  • 2
    This might help you https://stackoverflow.com/questions/39175252/cant-call-authuser-on-controllers-constructor – John Lobo Jul 22 '21 at 04:17
  • Suberb, @JohnLobo! It solved my issue. Thanks a lot. – Aditya Amit Jul 22 '21 at 04:27
  • 1
    Does this answer your question? [PHP parse/syntax errors; and how to solve them](https://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them) – matiaslauriti Jul 22 '21 at 05:09
  • 2
    A small recommendation, never use `$this->middleware();` in a controller, as that is the `route` responsibility (who allow access to or run any middleware), not the controller... If you were able to access that controller, then it means that the routing layer allowed you, do you see my logic ? – matiaslauriti Jul 22 '21 at 05:11

1 Answers1

0

Finally, I had to move the line of code auth()->user()->site to index() function next to the constructor as @John suggested. Also removed middleware from the controller and added to the web.php.

public function __construct(){
    $this->today = date("Y-m-d");        
}

public function index(){
    $this->sites = Helper::getSites(auth()->user()->site);
    return view('division.dashboard.index')->with($data);
}
Aditya Amit
  • 71
  • 2
  • 9