lundi 24 septembre 2018

Laravel - Update $guarded array based on different config

I have one model and one controller and multiple configurations.

If I'm on config #1 my models $guarded property should be

$guarded = ['foo', 'bar'];

If I'm on config #2 my models $guarded property should be only

$guarded = ['foo'];

The config loaded is dependant on a domain/subdomain.

In my controller I have an import function which takes an array of data. 4 or so of the fields need to go to one table which is common across all configs and the remaining values(which are variable depending on the config loaded) need to go into a separate pivot table. So one config might have 8 fields but another may have 9 or more / less.

I've tried to remove the variable fields from the insert into the first table with guarded with something similar to the code here. After which I take the variable fields and insert into the other table.

protected $guarded = ['some', 'common', 'guarded', 'fields'];

function __construct()
{
    $this->guarded = array_merge($this->guarded, config('custom_fields_for_domain'));
}

While I can dd($this->guarded) directly after and see the variable fields correctly in the model, I receive errors when trying to import into the first table as it's still trying to import all the variable fields rather than just the 4 or so fields I want.

If I manually add in all the variable fields, it works fine, so it seems that modifying $guarded even as early on as in the constructor doesn't work. It this correct? Is there a better way to modify the $guarded values based on different configurations?

I've not tried yet, but would I be better off using $fillable for just the fields I know are constant?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire