MorganFreeFarm
MorganFreeFarm

Reputation: 3733

Best way to handle additional fields in mass assignment in Laravel?

App\Models\Venue:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Venue extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'user_id', 'category_id', 'phone', 'address', 'content'];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

    public function city()
    {
        return $this->belongsTo(City::class, 'city_id');
    }

    public function features()
    {
        return $this->belongsToMany(Feature::class, 'venue_feature');
    }
}

StoreVenueRequest (rules part):

public function rules()
{
    return [
        'category_id' => 'required|integer',
        'title' => 'required|min:3',
        'city' => 'required|integer',
        'address' => 'required',
        'phone' => 'nullable|integer',
        'email' => 'nullable|email',
        'content' => 'required|min:10',
        'features' => 'required|min:3'
    ];
}

VenueController - store() method:

public function store(StoreVenueRequest $request)
{
    $venue = new Venue();
    $validated = $request->validated();
    $validated['user_id'] = auth()->id();
    $venue->create($validated);
    dd($venue);
}

Тhe code works perfectly, but I'm not sure this is the best way. Is there a way to avoid these two lines, mostly second one:

    $validated = $request->validated();
    $validated['user_id'] = auth()->id();

The only thing I can think of is hidden input field in the form with authenticated user id. I'm looking for the best way.

Upvotes: 0

Views: 415

Answers (1)

lagbox
lagbox

Reputation: 50561

You could merge an array with the $validated array:

Venue::create($validated + ['user_id' => auth()->id()]);

This is the same as moving it to the assignment of $validated:

$validated = $request->validated() + ['user_id' => auth()->id()];
Venue::create($validated);

No matter what you would have to merge arrays in some way before this point or at this point if you want this to be done with mass assignment. Otherwise you will be setting individual elements of an array, like you currently are doing.

Upvotes: 4

Related Questions