I've noticed strange behaviour over some Laravel
apps.
When I run lets say
Users::where("id",$request->input("id"))->update($request->input());
Sometimes it goes through fine. In other cases I get
Unknown column '_token' in 'field list'
So sometimes it only reads what is set in the $fillable
parameter, and other times it takes everything from $request->input()
. I keep comparing different models and see no difference. I know I can work around it by using the $request->only([])
method, but does anybody else have or had this issue and perhaps know a reason behind it?
Edit
This is my model.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BookingRequests extends Model
{
//
protected $fillable = array(
"account_id",
"quote_id",
"booking_id",
"website_id",
"color",
"custom_group_name",
"is_confirmed",
"ready_to_issue",
"created_by",
);
/**
* Return Quote
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function Quote(){
return $this->belongsTo('App\Quotes',"quote_id","id");
}
}
This is my controller
/**
* Update Booking Reques
* @param Request $request
*/
public function update(Request $request){
/**
* Validate
*/
$this->validate($request,array(
"id" => "required"
));
/**
* Update
*/
BookingRequests::where("id",$request->input("id"))->update($request->input());
/**
* Return
*/
return redirect()->back()->with("success","Booking updated");
}
This is being run on Laravel 5.3.31
To be honest what you are doing now is really risky. In fact it's possible now to update any fields no matter of $fillable
property. This is because you are now updating like this:
Users::where("id",$request->input("id"))->update($request->input());
When you are making update like this in fact you are making update directly in database and Eloquent things are not used so the query that is executed looks something like this:
UPDATE users SET a=1, b=2 WHERE id = 5
so if anyone sends existing columns in this table they will be updated what is very very risky because you don't want anyone to modify columns you don't want to.
But if you do something like this:
$user = Users::where("id",$request->input("id"))->firstOrFail();
$user->update($request->input());
In above case Eloquent is used (first you find record in database and it's Eloquent model and then you try to update this Eloquent model), so now it's possible to update only fields that are in $fillable
(assuming you are using 'fillable-way' but you do looking at your model). So now, no matter what is send in request, only fields in $fillable
will be updated.
Obviously above could be written in a bit shorter way:
$user = Users::findOrFail($request->input("id"));
$user->update($request->all());
or even in one like like this:
Users::findOrFail($request->input("id"))->update($request->all());