Home > database >  Eloquent relationship mass assignment $guarded ignored
Eloquent relationship mass assignment $guarded ignored

Time:09-15

I have three table in DB, and I have used belongsTo for merging them. My Admins model looks like this :

class Admin extends Authenticatable
{
    use HasFactory;

    protected $guarded = ['status', 'shop_name', 'vendor_id', 'id'];

    protected $guard = 'admin';
    public function getVendorDetails(){
        return $this->belongsTo(Vendor::class, 'vendor_id','vendor_id');
    }

    public function getVendorBusinessDetails(){
        return $this->belongsTo(VendorBusinessDetails::class, 'vendor_id','vendor_id');
    }

}

I need to prevent shop-name field to be saved through form. this field is in the table name : vendor_business_detals (getVendorBusinessDetails).But in this case $guarded only works for Admins table and ignores another relationship tables and fields of them such as shop_name. In short I am struggling to find the way to add $guarded data for VendorBusinessDetails. My controller looks like below:

 $business_data = $request->only(['shop_name', 'shop_address', 'shop_phone']);
//dd($business_data);
                    $myModel = Admin::find($id);
                    //business table update
                    $myModel->getVendorBusinessDetails()->update($business_data);

VendorBusinessDetails model:

class VendorBusinessDetails extends Model
{
    use HasFactory;
    protected $guarded = ['shop_name'];
    protected $table = 'vendors_business_details';
}

I don't know why $guraded=['shop_name'] is ignored. Any help would be highly appreciated.

CodePudding user response:

$myModel->getVendorBusinessDetails()->update($business_data);

If you use "getVendorBusinessDetails" as a method, the model isn't initialize. Only the SQL update command runs.

$myModel->getVendorBusinessDetails->update($business_data);

Using "getVendorBusinessDetails" as a field initializes the model. So, it works as you expected.

  • Related