Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel consider only the required columns from the request and ignore any other key values if present

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 set team_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 and tour_id = 10 and match_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?

like image 919
Vrajesh Doshi Avatar asked Feb 02 '18 12:02

Vrajesh Doshi


1 Answers

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();
like image 169
Laerte Avatar answered Nov 15 '22 09:11

Laerte