I'm building an API with Laravel 8.
I have a posts
table with these columns:
id
category_id
user_id
title
body
picture
study_time
likes
tags
When a user is logged in as an author or admin, they can add a new post.
and for user_id
field, I want to make that field guarded, I want to show username with JWTAuth::user()->username
and register it for user_id column.. so no one can enter any value for it
edit: when i send request it gives me this error: SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into posts
this is my store method in PostController:
$data = $request->all();
$validator = Validator::make($data, [
'category_id' => 'required',
'title' => 'required|max:100|unique:categories',
'body' => 'required',
'picture' => 'required',
'study_time' => 'required',
'tags' => 'null|string',
]);
if ($validator->fails()) {
return response(['error' => $validator->errors(), 'Validation Error']);
}
$tags = explode(",", $request->tags);
$post = Post::create($data);
$post->tag($tags);
return response()->json([
'username' => JWTAuth::user()->username,
'post' => $post
], 201);
add this after $data=$request->all():
$data['user_id'] = JWTAuth::user()->id;
or you can use this instead (if you define posts in user model):
JWTAuth::user()->posts()->create($data);
You can use $request->user()
to get the current user.
$post = Post::create($data);
$post->tag($tags);
$post->username => JWTAuth::user()->username
return response()->json([
'post' => $post
], 201);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.