I want to save new post from form in my database, I have title and body in $request and want to save logged in user's id in the post. how can i handle it in model or validation?
Validator::make($request->all(), [
'title' => ['required'],
'body' => ['required'],
])->validate();
Post::create($request->all());
I can save it as below:
$post = new Flight;
$post->title = $request->title;
$post->body = $request->body;
$post->user_id = $request->user()->id;
$post->save();
but I want better way.
Here's a sample code that I always use.
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
...
public function store(Request $request)
{
// take only fields that have been validated.
// instead of inserting all the request body
$validated = $request->validate([
'title' => 'required',
'body' => 'required'
]);
// use FormRequest if want seperate validation and its much cleaner
// something like this
// store(StorePostRequest $request)
// $validated = $request->validated();
// instead of declaring use Auth
// u can just use $request->user();
$post = $request->user()->post()->create($validated);
// or if you dont have the relation inside the user model
$post = Post::create(['user_id' => auth()->id()] + $validated);
return new JsonResponse($post, Response::HTTP_CREATED);
}
Include Authentication Facade in Controller header use Auth;
than you can use $post->user_id = Auth::id();
you can use both Auth::user()->id
or Auth::id()
. Thanks
You can use form request validation to extract validation login from the controller (seedocumentation ).
I'd suggest to use $request->validated()
method instead of $request->all()
to make sure that only expected fields are passed to the model.
Also, you can use a auth()->id()
helper method to get logged in user's ID.
So, the controller function could be as follows:
Post::create(array_merge($request->validated(), ['user_id' => auth()->id()]));
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.