vendredi 2 février 2018

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?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2BPXbs5
via IFTTT

Aucun commentaire:

Enregistrer un commentaire