laravel with mongodb ErrorException (E_WARNING) array_flip() - php

i want to use sub fillable array in model
protected $fillable = [
'requestInfo'=>[
'companyname',
'province',
'district',
'village',
'phone',
],
'owner'=>[
'fullname',
'province',
'district',
'village',
'nationality',
'fax',
'phone',
'factorynamela',
'factorynameen',
'located',
'locatprovince',
'locatdistrict',
'locatvillage',
'locatein'
],
];
but have error:
C:\xampp\htdocs\mocbizrrequest\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php
/**
* Determine if the model is totally guarded.
*
* #return bool
*/
public function totallyGuarded()
{
return count($this->getFillable()) == 0 && $this->getGuarded() == ['*'];
}
/**
* Get the fillable attributes of a given array.
*
* #param array $attributes
* #return array
*/
protected function fillableFromArray(array $attributes)
{
if (count($this->getFillable()) > 0 && ! static::$unguarded) {
return array_intersect_key($attributes, array_flip($this->getFillable()));
}
return $attributes;
}
}
Arguments
"array_flip(): Can only flip STRING and INTEGER values!"
ErrorException (E_WARNING)
array_flip(): Can only flip STRING and INTEGER values!
please help me thank
i want to use sub fillable array in model
in my model file
<?php
/**
* Created by IntelliJ IDEA.
* User: EXTRA
* Date: 4/5/2019
* Time: 11:48 AM
*/
namespace App\Model;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class RequestFrom extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'requestForm';
protected $fillable = [
'requestInfo'=>[
'companyname',
'province',
'district',
'village',
'phone',
],
'owner'=>[
'fullname',
'province',
'district',
'village',
'nationality',
'fax',
'phone',
'factorynamela',
'factorynameen',
'located',
'locatprovince',
'locatdistrict',
'locatvillage',
'locatein'
],
];
in controller file
namespace App\Http\Controllers;
use App\Model\RequestFrom;
use Illuminate\Http\Request;
class RequestFromController extends Controller
{
public function index()
{
$requestForms = RequestFrom::all();
return view('requestForm.index',compact('requestForms'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function create()
{
return view('requestForm.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'requestInfo'=>[
'companyname' => 'required',
'province' => 'required',
'district' => 'required',
'village' => 'required',
'phone' => 'required'
],
'owner'=>[
'fullname' => 'required',
'province' => 'required',
'district' => 'required',
'village' => 'required',
'nationality' => 'required',
'fax' => 'required',
'phone' => 'required',
'factorynamela' => 'required',
'factorynameen' => 'required',
'located' => 'required',
'locatprovince' => 'required',
'locatdistrict' => 'required',
'locatvillage' => 'required',
'locatein' => 'required'
],
]);
RequestFrom::create($request->all());
return redirect()->route('requestForm.index')
->with('success','created successfully.');
}

Related

Laravel Backpack List function not working

When I load the page, it gives me an error and tells me to reload.
However, when I add data to the database it works properly.
So, basically my list function isn't working and I don't know why.
I checked for typos, it can't be something like updating, because of all my other CRUD's work fine with the same method.
Controller :
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Requests\ProjectRequest;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
/**
* Class ProjectCrudController
* #package App\Http\Controllers\Admin
* #property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
*/
class ProjectCrudController extends CrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
public function setup()
{
$this->crud->setModel('App\Models\Project');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/project');
$this->crud->setEntityNameStrings('project', 'projects');
}
protected function setupListOperation()
{
$this->crud->setColumns([
'name' => 'status',
'type' => 'text',
'label' => 'Status'
]);
$this->crud->setColumns([
'name' => 'topic',
'type' => 'text',
'label' => 'Topic'
]);
$this->crud->setColumns([
'name' => 'leader',
'type' => 'text',
'label' => 'Leader'
]);
$this->crud->setColumns([
'name' => 'email',
'type' => 'text',
'label' => 'Name'
]);
$this->crud->setColumns([
'name' => 'tags',
'type' => 'text',
'label' => 'Tags'
]);
}
protected function setupCreateOperation()
{
$this->crud->setValidation(ProjectRequest::class);
$this->crud->addField([
'name' => 'status',
'type' => 'text',
'label' => 'Status'
]);
$this->crud->addField([
'name' => 'topic',
'type' => 'text',
'label' => 'Topic'
]);
$this->crud->addField([
'name' => 'leader',
'type' => 'text',
'label' => 'Leader'
]);
$this->crud->addField([
'name' => 'email',
'type' => 'text',
'label' => 'Name'
]);
$this->crud->addField([
'name' => 'tags',
'type' => 'text',
'label' => 'Tags'
]);
}
protected function setupUpdateOperation()
{
$this->setupCreateOperation();
}
public function store()
{
$this->crud->hasAccessOrFail('create');
// execute the FormRequest authorization and validation, if one is required
$request = $this->crud->validateRequest();
// insert item in the db
$item = $this->crud->create($this->crud->getStrippedSaveRequest());
$this->data['entry'] = $this->crud->entry = $item;
// show a success message
\Alert::success(trans('backpack::crud.insert_success'))->flash();
// save the redirect choice for next time
$this->crud->setSaveAction();
return $this->crud->performSaveAction($item->getKey());
}
}
Model:
<?php
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use CrudTrait;
/*
|--------------------------------------------------------------------------
| GLOBAL VARIABLES
|--------------------------------------------------------------------------
*/
protected $table = 'projects';
// protected $primaryKey = 'id';
// public $timestamps = false;
protected $guarded = ['project_id'];
protected $fillable = ['topic', 'status', 'leader', 'email', 'tags'];
// protected $fillable = [];
// protected $hidden = [];
// protected $dates = [];
/*
|--------------------------------------------------------------------------
| FUNCTIONS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| SCOPES
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| ACCESSORS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| MUTATORS
|--------------------------------------------------------------------------
*/
}
Request:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Foundation\Http\FormRequest;
class ProjectRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
// only allow updates if the user is logged in
return backpack_auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'topic' => 'required|min:5|max:255',
'status' => '',
'leader' => 'required|min:5|max:255',
'email' => 'required|min:5|max:255',
'tags' => 'required|min:5|max:255'
];
}
/**
* Get the validation attributes that apply to the request.
*
* #return array
*/
public function attributes()
{
return [
//
];
}
/**
* Get the validation messages that apply to the request.
*
* #return array
*/
public function messages()
{
return [
//
];
}
}
protected $primaryKey = 'project_id';
Database had project_id instead of just id, so this should work.

Laravel relationship is not loading in Resource?

I want to load the relation of order with customer but it is returning null in the postman
Customer Model
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Customer extends Authenticatable implements JWTSubject
{
use Notifiable;
protected $fillable = [
'first_name',
'last_name',
'phone_number',
'postal_code',
'email',
'preferred_method_to_contact',
'password',
'address',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getNameAttribute()
{
$name = $this->first_name . " " . $this->last_name;
return $name;
}
public function orders()
{
return $this->hasMany('App\Order');
}
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
Order Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'phone_number',
'post_code',
'address',
'alternative_address',
'property_type',
'property_type_other',
'contract_type',
'contract_type_other',
'no_of_bedrooms',
'no_of_bathrooms',
'customer_id',
'best_day',
'best_time',
'type_of_cleaning',
];
public function customers()
{
return $this->belongsTo('App\Customer');
}
}
Order Resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class OrderResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
/*return parent::toArray($request);*/
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone_number' => $this->phone_number,
'post_code' => $this->post_code,
'address' => $this->address,
'alternative_address' => $this->alternative_address,
'property_type' => $this->property_type,
'property_type_other' => $this->property_type_other,
'contract_type' => $this->contract_type,
'contract_type_other' => $this->contract_type_other,
'no_of_bedrooms' => $this->no_of_bedrooms,
'phone_number' => $this->phone_number,
'no_of_bathrooms' => $this->no_of_bathrooms,
'customer' => new CustomerResource($this->whenLoaded('customers')),
];
}
}
Customer Resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CustomerResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
/*return parent::toArray($request);*/
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
];
}
}
Here is the function in OrderController which is responsible for sending the JSON response
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'first_name' => ['required', 'string', 'max:10'],
'last_name' => ['required', 'string', 'max:10'],
'email' => ['required', 'string', 'email', 'max:50'],
'phone_number' => ['required', 'string', 'max:30'],
'post_code' => ['required', 'string', 'max:30'],
'address' => ['required', 'string', 'max:300'],
'alternative_address' => ['required', 'string', 'max:300'],
'property_type' => ['required', 'string', 'max:30'],
'contract_type' => ['required', 'string', 'max:30'],
'no_of_bedrooms' => ['required', 'string', 'max:30'],
'type_of_cleaning' => ['required', 'string', 'max:30'],
'best_day' => ['required', 'string', 'max:30'],
'best_day' => ['required', 'string', 'max:30'],
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
// $customer = Customer::findOrFail($request->customer_id);
$order = Order::create($request->all());
// $order = Order::create();
$order->load(array('customers'));
return new OrderResource($order);
}
I want the customer details to be loaded along with the order.
Somehow I managed to fix that problem. Actually the ManyToOne relationship function was not recognizing the customers. The customers function targets the many-to-one so it should be singular instead of plural according to the standards of laravel.
public function customer()
{
return $this->belongsTo('App\Customer');
}
Similarly in the OrderController
$order->load(array('customer')); // <- make it singular as well
In the OrderResource
'customer' => new CustomerResource($this->whenLoaded('customer')), // <- make it singular

How to implement join query in Yii2

I've read all the Yii2 Framework documentation but it's confusing when trying to implement it.
I have a view of Customer where it shows all the fields in customer table, including the address_id field in the address table.
I want to implement a join query using MySQL in the Yii2 Framework but the generated code is the following:
CustomerSearch in the models:
class CustomerSearch extends Customer{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['customer_id', 'store_id', 'address_id', 'active'], 'integer'],
[['first_name', 'last_name', 'email', 'create_date', 'last_update'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Customer::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'customer_id' => $this->customer_id,
'store_id' => $this->store_id,
'address_id' => $this->address_id,
'active' => $this->active,
'create_date' => $this->create_date,
'last_update' => $this->last_update,
]);
$query->andFilterWhere(['like', 'first_name', $this->first_name])
->andFilterWhere(['like', 'last_name', $this->last_name])
->andFilterWhere(['like', 'email', $this->email]);
return $dataProvider;
}
Customer class:
class Customer extends \yii\db\ActiveRecord{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'customer';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['store_id', 'first_name', 'last_name', 'address_id'], 'required'],
[['store_id', 'address_id', 'active'], 'integer'],
[['create_date', 'last_update'], 'safe'],
[['first_name', 'last_name'], 'string', 'max' => 45],
[['email'], 'string', 'max' => 50],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'customer_id' => 'Customer ID',
'store_id' => 'Store ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email',
'address_id' => 'Address ID',
'active' => 'Active',
'create_date' => 'Create Date',
'last_update' => 'Last Update',
];
}
}
You need to declare some relations in your ActiveRecord models...
See here in the official docs for Working with Relational Data
If you are storing the address_id in your customer table then you will be tied to each customer having 1 single address (i.e. a one-to-one relationship), which is a rather bad design. Or you could use a junction table. You are better off storing the customer_id in each address record and defining a one-to-many relation, enabling each customer to store multiple addresses (more like in real life, i.e. for home, work address etc).
For example, in your Customer model, you would define a has-many relation for customer addresses:
use app\models\Address;
class Customer extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'customer';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['store_id', 'first_name', 'last_name', 'primary_address_id'], 'required'],
[['store_id', 'primary_address_id', 'active'], 'integer'],
[['create_date', 'last_update'], 'safe'],
[['first_name', 'last_name'], 'string', 'max' => 45],
[['email'], 'string', 'max' => 50],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'customer_id' => 'Customer ID',
'store_id' => 'Store ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email',
'primary_address_id' => 'Primary Address ID',
'active' => 'Active',
'create_date' => 'Create Date',
'last_update' => 'Last Update',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAddresses()
{
return $this->hasMany(Address::className(), ['customer_id' => 'id']);
}
}
And in your Address model you would have the inverse has-one relation defined:
/**
* #return \yii\db\ActiveQuery
*/
public function getCustomer()
{
return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
}
You can then Access relational data from model instances via defined relation names, for example:
// SELECT * FROM `customer` WHERE `id` = 123
$customer = Customer::findOne(123);
// SELECT * FROM `address` WHERE `customer_id` = 123
// $addresses is an array of Address objects
$addresses = $customer->addresses;
Also note, if you define proper primary/foreign keys in your schema, the Gii Model/CRUD generators will automatically create the boilerplate relations code in your models and CRUD files.

YII 2 relational data from third table

I have a database having relationship of three levels. cheque->account->customer. Now I am trying to retrieve data from all three table at same time using the following method.
$query = Cheque::find();
$query->joinWith(['account.customer']);
$query->orderBy('sr desc');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
Cheque Model:
class Cheque extends \common\components\db\ActiveRecord {
/**
* #inheritdoc
*/
public static function tableName() {
return 'cheque';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['sr'], 'integer'],
[['ID', 'account_ID'], 'required'],
[['ID', 'account_ID', 'created_by', 'branch_ID', 'application_ID'], 'string'],
[['serial_start', 'serial_end', 'status'], 'number'],
[['created_on'], 'safe']
];
}
/**
* #inheritdoc
*/
public function attributeLabels() {
return [
'ID' => 'ID',
'account_ID' => 'Account ID',
'serial_start' => 'Serial Start',
'serial_end' => 'Serial End',
'created_on' => 'Created On',
'created_by' => 'Created By',
'branch_ID' => 'Branch ID',
'application_ID' => 'Application ID',
'status' => 'Status',
'sr' => 'ID'
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAccount() {
return $this->hasOne(Account::className(), ['ID' => 'account_ID']);
}
public static function getActiveChequeBook($account_ID) {
return Cheque::findAll(['account_ID' => $account_ID, 'status' => array_search('Active', \common\models\Lookup::$cheque_status)]);
}
}
But executing this I get the following error:
pre>Exception 'yii\base\InvalidCallException' with message 'Setting read-only property: common\models\Account::customer'
Property customer in your common\models\Account model has no setter (only getCustomer method exists). Check you model and add appropriate property to class.

Laravel Registration ERROR With UNKnown Field

the script returns an error that i don't think i included in my code.
SQLSTATE[HY000]: General error: 1364 Field 'phone' doesn't have a default
value (SQL: insert into `users` (`name`, `email`, `location`, `password`,
`steps`, `incubation_days`, `updated_at`, `created_at`) values (ilamini
Ayebatonye Dagogo, dagogo#gmail.com, Uniben Road, Ugbowo, Benin City, Nigeria,
$2y$10$aoJRS61Bn/q1eNcUFALjne8erLXD11y1.OmHhurlQJDrex73DPWJW, settings, 8,
2017-03-01 14:11:54, 2017-03-01 14:11:54))
Can someone point me to where this phone field is coming from.
Below my Register Controller Class.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\paring_by_location;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'location' => 'required|min:5',
'name' => 'required|max:255',
'password' => 'required|min:6|confirmed',
'email' => 'required|email|max:255',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$phDay = rand(2,8);
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'location' => $data['location'],
'password' => bcrypt($data['password']),
'steps' => 'settings',
'incubation_days' => $phDay
]);
paring_by_location::create([
'name' => $data['name'],
'email' => $data['email'],
'location' => $data['location'],
]);
event(new \App\Events\UserReferred(request()->cookie('ref'), $user));
return $user;
}
}
and Below is my HomeController that i think may be Interfering with the Register Controller.
public function AccountSettings(Request $request)
{
$id = Auth::user()->id;
$user = User::findOrFail($id);
$this->validate($request, [
'account_name' => 'required|string|min:5',
'account_number' => 'required|digits:10',
'bank_name' => 'required|string|min:3',
'phone' => 'required|digits:11'
]);
$input = $request->all();
$user->update(array('steps' => 'notification'));
$update = $user->fill($input)->save();
return redirect()->route('home');
}
also is my USER MODEL TAHT has the protected field
protected $fillable = [
'name', 'email', 'password', 'location','steps','incubation_days','phone','bank_name','account_name','account_number',
];
So I want to understand why it is returning an error when i did not include the phone in the register controller
You should set nullable() or default() value for the phone field. It should look like this in migration for users table:
$table->string('phone')->nullable();
Or make the phone field required:
protected function validator(array $data)
{
return Validator::make($data, [
'location' => 'required|min:5',
'name' => 'required|max:255',
'password' => 'required|min:6|confirmed',
'email' => 'required|email|max:255',
'phone' => 'required'
]);
}
And add it to create() method:
create([
'name' => $data['name'],
'email' => $data['email'],
'location' => $data['location'],
'phone' => $data['phone']
]);

Categories