Home > other >  Using Laravel Policy and add key and value to request
Using Laravel Policy and add key and value to request

Time:09-20

the user can create new object and to be sure, that the new object is connected to the correct user I had the idea to write a hidden field with user_id of the current logged in user:

<input style="display:none" name="group_id" type="number" value="{{ Auth()->User()->group_id }}">

Now the problem is that someone can change the value here and create the objekt for another number.

I want to be sure and check it in the backend or delete the hidden field and add the value to the request. Currenty my store method looks like :

public function store(StoreObjektRequest $request)
    {   
        if (Auth()->User()->group_id != $request->group_id) 
        abort(403);

        $this->authorize('create', Objekt::class);
        
        Objekt::create($request->validated());
        return redirect()->route('dashboard')->with('message', 'Objekt erfolgreich erstellt');
    }

My Rules are:

public function rules()
    {
        return [
            'name' => 'required|max:5',
            'strasse' => 'required',
            'hausnummer' => 'required',
            'plz' => 'required',
            'ort' => 'required',
            'group_id' => 'required',
        ];
    }

My Question is: Which is the best way to check the group_id for the new created object. I tried to merge the value to the request, but my own StoreObjektRequest is waiting for the group_id which is required. Maybe I could use my policy which is currently returning true.

CodePudding user response:

Remove the group_id as an input and remove it from the validation as it isn't going to be user input but you are going to get it from the currently authenticated user instead. You can get the inputs that are validated from the request and then merge the group_id into that array:

Objekt::create(auth()->user()->only('group_id')   $request->validated());

Just make sure group_id is "fillable" on that model.

  • Related