phplaravellaravel-6laravel-authenticationlaravel-controller

Laravel 6 how to store logged user's id in controller


I am trying to store logged user's id but I am getting this error

ErrorException
array_map(): Argument #2 should be an array

This is the code in the controller

    public function store(Request $request)
    {
        if (!auth()->check()) {
            abort(403, 'Only authenticated users can create new posts.');
        }

        $data = request()->validate([
            'id' => $id  = Auth::id(),
            'content' => 'required',
            'topic' => 'required',
            'hashtag' => 'required'
            ]);

            $check = Tweets::create($data);
            return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
    }

The error is in this line of code.

'id' => $id  = Auth::id(),

I know that should be a string but to explain to you what I am trying to do, and I still have not found any solution.


Solution

  • Do it Like this.

    public function store(Request $request)
    {
                if (!auth()->check()) {
                    abort(403, 'Only authenticated users can create new posts.');
                }
        
                $request->validate([
                    'content' => 'required',
                    'topic' => 'required',
                    'hashtag' => 'required'
                    ]);
                $data = $request->all();
                $data['id'] = Auth::id();
                $check = Tweets::create($data);
                return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
    }