-1

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.

  • user_id is not nullable in DB
mehri abbasi
  • 145
  • 1
  • 11
  • What is the problem exactly whatever you have done look correct. – Prashant Deshmukh..... Dec 02 '20 at 05:52
  • `$request->user()->id` this gives you the authenticated logged in user, so what is the issue here? – Anuj Shrestha Dec 02 '20 at 06:17
  • I want to handle this in model or validation and in controller's code just have Post::create($request->all());. Actually same as timestamps that Laravel handles itself or default value for fields , I want to handle this too – mehri abbasi Dec 02 '20 at 06:21
  • One thing to understand is `$request->all()` gives you the array of your form inputs with names. If you don't have any input in your form for `user_id` you simply won't get it in `$request`. Either define that input or keep doing what you have already done. The approach @Muddassir has shown is also a good way to get authenticated user's id. – Saud Dec 02 '20 at 06:42
  • Yes, I know about forms and requests , I want to handle this automatically. For example if add protected $attributes = [ 'user_id' => 1, ]; , number 1 always save for user_id , now I want user's id instead of number 1 – mehri abbasi Dec 02 '20 at 06:47
  • @mehriabbasi what you have asked above and what you're asking now are two different things. Please rephrase your question so that you can get specific answers. And for the approach you want to use, you cannot just initialize a non-constant value. [For Read...](https://stackoverflow.com/questions/40827870/constant-expression-contains-invalid-operations) – Saud Dec 02 '20 at 07:38

3 Answers3

2

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);
}
Aslam H
  • 1,669
  • 4
  • 21
  • 46
  • $post = Post::create(['user_id' => auth()->id()] + $validated); this one didn't work for me. but the one based on relation was ok, thanks – mehri abbasi Dec 02 '20 at 14:48
1

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

Muddassir Izhar
  • 127
  • 1
  • 8
0

You can use form request validation to extract validation login from the controller (see documentation).

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()]));
Nikolai Kiselev
  • 6,201
  • 2
  • 27
  • 37