fest's avatar
Level 1

Unable to store data in database

Hi fellow artisans, this error "Attempt to read property "id" on null" keeps popping up when I try to store my data in the database, this is my controller.

public function store(Request $request){ $request->validate([ 'title' => 'required', 'image' => 'required | image', 'body' => 'required' ]);

    $title = $request->input('title');
    $slug = Str::slug($title, '-');
    $user_id = Auth::user()->id;
    $body = $request->input('body');

    // file upload
    $request->file('image')->store('public');

    dd('validation successful');
0 likes
6 replies
lbecket's avatar
lbecket
Best Answer
Level 39

It appears that you don't have an authenticated user. What do you get when you run dd(Auth::user);?

2 likes
Sinnbeck's avatar

@fest if it's solved you can close the thread by marking a best answer

MohamedTammam's avatar

Make sure there's an authenticated user

if(Auth::check()) {
	$title = $request->input('title');
    $slug = Str::slug($title, '-');
    $user_id = Auth::user()->id;
    $body = $request->input('body');
    // file upload
    $request->file('image')->store('public');
} else {
	// Handle not having a user case.
 }
1 like
Sinnbeck's avatar

Add the auth middleware to the route to ensure that the user is logged in

Please or to participate in this conversation.