Skip to content
Advertisement

prevent updating some fields defined as filable on update a model

Suppose we have a model like this :

class BankAccount extends Model
{
    protected $fillable = ['title', 'rate', 'bank_id', 'account_number', 'active'];
{

As you can see there is a $fillable property.

When storing a new model I used these codes :

public function store(BankAccountFormRequest $request)
{

        BankAccount::create($request->all());
}

In this case a new BankAccount model created with fields that come from request.

But suppose in updating same model like this :

public function update(BankAccountFormRequest $request, $id)
{
    $bankAccount = BankAccount::findOrFail($id);
    $bankAccount->update($request->all());
}

In this case , I do not want to update some attributes that are fillable. for example I want to update just title, rate and I do not want user can update other fields. but if User client send all fields as a request those fields will be update too.

Also I know that a way to solve the issue is use save() method like this :

public function update(BankAccountFormRequest $request, $id)
{
    $bankAccount = BankAccount::findOrFail($id);

    $bankAccount->user_id = $this->auth->user()->user_id;
    $bankAccount->accountable_id = $request->get('accountable_id');
    $bankAccount->accountable_type = $request->get('accountable_type');

    $bankAccount->save();

}

But I think that is not appropriate when count of desired columns to update is many.

What is real approach to solve that ?

Advertisement

Answer

You can user $request->only to filter parameters, optionally you can keep ['username', 'password'] as a static property of the model.

$request->only(['username', 'password']);

But inserting updating data directly from $request->all() will not be a good idea unless proper error handling is implemented. Eg, an extra parameter send in request will cause an error.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement