Polecalex's avatar

User data within Controller

Hello, I am trying to make an image upload controller, all data is input into the database however the author which is supposed to be the user's id however whatever I use I am not able to get the user's id. I have used the following: Auth::user()->id and $request->user()->id Is there any way to get the id from the currently logged in user while you're setting the data within the controller.

0 likes
9 replies
Snapey's avatar

Auth::user()->id or Auth::id() or $request->user()->id

It doesn't sound like getting the ID is the problem

Why not show the code where you reference it?

Polecalex's avatar

@SNAPEY - Sorry, I just didn't think it was necessary, here is the full function.

public function createPost(Request $request)
{

        $data['title'] = $request['title'];
        $data['author'] = $request->user()->id;
        $data['description'] = $request['description'];

        if($request->hasfile('img'))
        {
            $name = $request->file('img')->getClientOriginalName();
            $request->file('img')->move(public_path().'/imgs/', $name);
            $data['img'] = $name;
        }

        $data['tags'] = $request['tags'];

        Post::create($data);
        return redirect()->route('home');
}
Snapey's avatar

so, as you are using create (mass assignment), is user_id in your $fillable array?

sorry, author field

Polecalex's avatar

@SNAPEY - Yes it is, every index of the data array is in the fillable. I logged the user id before assigning it and it shows the correct Id with Auth::id() so I believe there is a problem when I try to assign it to $data['author']

shez1983's avatar
shez1983
Best Answer
Level 23

try this :

$post = new Post();
$post->author = \Auth::id();
$post->fill($data) // make sure you comment/remove this line: $data['author'] = $request->user()->id;
$post->save();
Polecalex's avatar

@SHEZ1983 - This worked, thank you.

Is anyone able to explain why it wasn't setting with the $data['author'] = \Auth::id() as this is still confusing me. I would assume this would work however it just doesn't want to set the value for some reason.

Snapey's avatar

based on the code you show there should be no difference in the two approaches

Please or to participate in this conversation.