In the Laravel API, I am passing the request input json with few additional key:values which I require in other part of the business logic of the API function. When I pass the array $request->all()
, of the formal parameter Request $request
of the Controller function to the Model function and directly pass it to the Eloquent create()
function as follows:
StatusModel::create($request);
I get the error,
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'app' in 'field list' (SQL: update
tbl_points
setteam_id
= 4,tour_id
= 10,match_id
= 254,win
= 0,loss
= 1,tie
= 1,n_r
= 1,pt
= 1,nrr
= 1,app
= 3 where (team_id
= 4 andtour_id
= 10 andmatch_id
= 254)).
I want to pass the input request array as it is and want the laravel to ignore the columns name keys from the array which are not present in the database. EG: Following is my input json, in which "app":3 is an extra key value not present in table.
{
"team_id": 4,
"tour_id": 10,
"match_id": 254,
"win": 0,
"loss": 1,
"tie": 1,
"n_r": 1,
"pt": 1,
"nrr": 1,
"app": 3
}
My Model Code
<?php
namespace App\Models\BaseModels;
use Illuminate\Database\Eloquent\Model;
class TablePoints extends Model
{
protected $table = 'tbl_points';
protected $fillable = ['team_id','tour_id','match_id','win','loss','tie','n_r','pt','nrr'];
public $timestamps = false;
}
On dd($request->all()) I get the following in output:
array:10 [
"team_id" => 4
"tour_id" => 10
"match_id" => 254
"win" => 0
"loss" => 1
"tie" => 1
"n_r" => 1
"pt" => 1
"nrr" => 1
"app" => 3
]
How to avoid getting such errors by making code ignore extra key value pairs.
Note: I don't want to create a new array and copy values of required keys from request array and use it. Is there any other solution?
You should use except
function. Try this:
StatusModel::create($request->except('app'));
This will return all fields except for app
field.
You can also use it with an array to ignore multiple fields. Ex:
$request->except(['field1', 'field2']);
If you need to exclude all irrelevant data, you can use a code hack like this:
In StatusModel:
public function getFillable()
{
return $this->fillable;
}
And then in Controller, use only
method to filter the attributes in request:
$statusModel = new StatusModel();
$fields = $request->only($statusModel->getFillable());
$statusModel->fill($fields);
$statusModel->save();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With