Monday, May 22, 2017

How to call Auth::id() in controllers for frontend

I'm trying to call the id of my user in my controllers for my frontend. In the backoffice Auth::id() works like a charm, but when I try to call it in the controllers for my backoffice I get an error that my user_id cannot be null. Meaning that Auth::id() doesn't seem to work. So it seems like Laravel only recognises a signed in user in the backoffice and I don't know why.

This is the store function of my controller for my frontend:

 public function store(Request $request)
    {
        $optionElection = new OptionElection();
        //this returns null
        $optionElection->user_id = Auth::id();
        // this also returns null 
        $optionElection->option = Auth::name();
        $optionElection->votes = 0;
        $optionElection->election_id = $request['election_id'];
        $optionElection->accepted = 0;

        if ($optionElection->save()) {


            return response()
                ->json($optionElection);

        }

    }

When I tried to store I always checked that I'm logged in in the backoffice with Laravel Auth.



via hxwtch

Advertisement