Description
$category = Category::create($validated);
on this line, it shows this error:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value
on dd() it is getting user id .
View Code
public function store(StoreCategoryRequest $request)
{
$validated = $request->validated();
$validated['slug'] = Str::slug($validated['name'], '_', true);
$validated['user_id'] = Auth::id();
$category = Category::create($validated);
session()->flash('message', 'Successfully created the ' . $validated['name'] . ' category');
return redirect()->route('categories.index');
}
This error you are facing is due to the null value of user_id.
As you mentioned your column name is user_id and you are passing its value as Auth::id() so it will return the login user id, but the problem is that your login session was expired and Auth::id() is returning the null value, that's you are facing this issue, if you will login the user so this problem will be solved, but hold on.
Login the user isn't the permanent solution, you can apply a check that if the user is not logged in then you will redirect the user to the login page to login the user and then create the category.
~~~
if (Auth::id() == null) {
return redirect('login');
}
$category = Category::create($validated);
~~~
In this way, your user will be able to create the category when he is logged in.
0 Likes 1 Comment
Hadayat Niazi Super Admin
Please let us know if this problem was solved?