Reputation: 6612
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 ?
Upvotes: 3
Views: 2828
Reputation: 31
As an enhancement for Jithin's answer: You can define 'updatable' fields list in the Model.
public function updatables(){
return ['title','rate'];
}
Then call it from Controller:
$bankAccount->update($request->only(BankAccount::updatables()));
Or do the opposite by defining the 'non updateables' and call
$bankAccount->update($request->except(BankAccount::nonUpdatables()));
Upvotes: 0
Reputation: 1821
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.
Upvotes: 4