Laravel Eloquent saveMany does not accept second attribute - php

As I think it is typically as the documentaion I have tried to use saveMany regarding its parameters as Model objects.
I have a model named Set and it hasMany Equipment so, from the from that creates a set I submit many fields of Equipment in-order to be saved as the following:
//Store method of SetController
$set = new Set();
$set->title = request('title');
$set->eqtype_id = request('eqtype');
$set->product_id = request('product');
$set->parts_count = request('parts_count');
$eq = request('equipments');
$set->equipments()->saveMany(array_map(function($n){return new \App\Equipment(['title' => $n, 'eqtype_id' => request('eqtype')]);}, $eq));
$set->save();
However, I always get the error message about that eqtype_id does not has a default value:
SQLSTATE[HY000]: General error: 1364 Field 'eqtype_id' doesn't have a
default value (SQL: insert into equipments (title, set_id,
updated_at, created_at) values (A-1, , 2017-03-18 12:07:30,
2017-03-18 12:07:30))
I thought that, may be, request('eqtype') is not accessible from the array_map callback, so I replaced it with a fixed number as follows:
$set->equipments()->saveMany(array_map(function($n){return new \App\Equipment(['title' => $n, 'eqtype_id' => 1]);}, $eq));
But also the error is same, it seems like a problem with either saveMany or array_map. I don't know how to fix this issue!
Notice
The model Equipment is related with the both model Set and Eqytpe as follows:
//Equipment model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* App\Equipment
*
* #mixin \Eloquent
*/
class Equipment extends Model
{
public $table = "equipments";
protected $fillable = ['title'];
public function set()
{
return $this->belongsTo(Set::class);
}
public function eqtype()
{
return $this->belongsTo(Eqtype::class);
}

I kind of had the same problem and this is what I did to fix it:
I had a One to Many relationship between a Product and Image and I wanted on a product creation add all the images related to it
// Create post
public function store(Request $request)
{
$newProduct = Product::create([
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
'stock_items' => $request->stock_items,
]);
for ($i = 0; $i < count($request->image_path); $i++) {
$newProduct->image()->saveMany([
new Image(['image_path' => $request->image_path[$i]])
]);
}
}
Don't forget the relationship functions & to create multiple input with the same name : name='image_path[]'

Related

How to retrieve all data from three tables according to groupby of second table's field value using Laravel eloquent query?

I have three models with some methods like
1.Employee Model
class Employee extends Model
{
protected $fillable = [
'employee_no','card_no','inactivedate', 'activedate', 'status',
];
public function office(){
return $this->hasOne(EmployeeOffice::class);
}
public function section(){
return $this->belongsTo('App\Hrm\Section');
}
}
2.EmployeeOffice Model
class EmployeeOffice extends Model
{
$fillable = ['employee_id','section_id','line_id','join_date','gross','confirm_date'];
public function employee(){
return $this->belongsTo(Employee::class);
}
public function section(){
return $this->belongsTo('App\Hrm\Section');
}
}
3.Section model....
class Section extends Model
{
protected $fillable = ['name','description','status'];
//
}
i need all inactive employee information according to the employee inactive date(from employee model) as well as their all office information from EmployeeOffice model and must be groupBy according to section_id which is (section_id as foreign key) available in EmployeeOffice model.
For that i have to go with some condition like ..
Employee::where('inactivedate','like','%'.$date.'%');
*And need all data from office and employee table
*need section name and grouped by as section name from section model
***please suggest me how can i solve this problem ***
Try this:
$data = Section::with(
array(
'employeeOffice' => function(
$query->with(
'employees' => function(
$query->where('employees.inactivatedate', 'like', '%'.$date.'%'
)
)
)
)
)
->get();
This should give you an array to every section_id. In this array are the employeeOffices (1:n-Relationship). The second query with with will fetch for each employeeOffice the employee who sits in it.
But if you defined the relationships right, this should do the trick to:
Section::with('EmployeeOffice.Employee')->get();
Nested Eager Loading
I have solved my problem by this...
if(Input::has('start') && Input::has('end')){
$start = Carbon::parse(Input::get('start'))->startOfDay();
$end = Carbon::parse(Input::get('end'))->endOfDay();
$start = $start->format('Y-m-d');
$end = $end->format('Y-m-d');
EmployeeOffice::query()->whereHas('employee',function ($query) use ($start,$end){
$query->whereBetween('inactivedate',[$start, $end])->where('status',0);
})->paginate()->groupBy('section_id');
}

unable to save foreign key into my table using laravel 5.5

i am trying to save foreign key which coming from another table into my controller method but i am unable to save this and stuch in this issue:
what i am trying to do here is there is business_id which is FK coming from business_master table:
My controller method:
$businessId = Input::get('business_id');
$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url = Input::get('page_url');
$page->business()->attach($businessId);
$page->business_id = $businessId;
$page->save();
$resultArray = ['status' => 1, 'message' => 'Page url added!', 'dataArray' => $page];
}
and my page model:
class Page extends Model
{
protected $table = 'page_master';
protected $fillable = ['business_id','page_url','page_name'];
public function business()
{
return $this->hasMany('App\Business','business_id','id');
}
error i am getting here is
BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::attach()
i desperately want to store business_id (fk) but i am unable to do that your any help will be highly appreciated!
You have an error because only instance can be attached in many to many relationsip
$page->business()->attach($businessId);
Try bussiness create()
$page->business()->create([]);
Remove the line
$page->business()->attach($businessId);
Use only
$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url = Input::get('page_url');
$page->business_id = $businessId;
$page->save();
The code will work for you.
It's good that you are using $fillable as it's help In the Eloquent ORM to avoid the mass assignment of such fields, we define the list of fields in the model under the fillable, so that when we send the array of values to model it will directly process the operation on depends upon the action like create, update, delete, etc.

Laravel 5.2 - Query Builder Syntax To Filter Polymorphic Relationship?

I have the following query where I want to filter a polymorphic relationship:
$companyLogo = $user->company->files->where('file_type', 'Logo')->first();
When I enable the query log this is what I get:
"query" => "select * from `files` where `files`.`fileable_id` = ? and `files`.`fileable_id` is not null and `files`.`fileable_type` = ?"
"bindings" => array:2 [▼
0 => 1
1 => "App\Company"
]
As you can it is not including my where clause?
* Update *
This is the polymorhpic relationship I have between company and file models:
class File extends Model {
protected $fillable = [
'name',
'path',
'size',
'mime_type',
'file_type',
'fileable_id',
'fileable_type',
];
public function fileable()
{
return $this->morphTo();
}
}
class Company extends Model {
public function files()
{
return $this->morphMany('App\File', 'fileable');
}
}
I'm not sure why the query inst including the where clause either. Is the syntax correct to filter a polymorphic relationship? A company can have different types of files e.g. documents, logo etc but I want to select the logo.
I decided to refactor as follows:
Added a query scope to the File class:
public function scopeCompanyLogo($query, $id)
{
$query->where('file_type','=', 'Logo')
->where('fileable_type','=', 'App\Company')
->where('fileable_id','=', $id);
}
Now get the company logo as follows:
$companyLogo = File::CompanyLogo($user->company_id)->first();
* Update *
Just figured what was wrong with original code too
Instead of doing this:
$companyLogo = $user->company->files->where('file_type', 'Logo')->first();
It should have been:
$companyLogo = $user->company->files()->where('file_type', 'Logo')->first();

Laravel 5 instantiate model with where clause

In my controller, I want to be able to call the model Category and give it an array ('dbField' => 'value') and I want to be able to use this array in a where clause.
My Controller:
$categories = new Category(['name' => 'category name']);
My Model:
public function __construct($attributes = [])
{
parent::__construct($attributes);
...
}
But it doesn't seem to work that way, whenever you pass attributes to the model constructor it's only for mass assignement, is there any way to do that ?
The constructor is for filling attributes.
You can try an actual where
$attributes = ['name' => 'blah'];
$findIt = Category::where($attributes)->get(); // or first();
// get the first matched record based on the attributes or return a new instance filled with those attributes
$findItorNot = Category::firstOrNew($attributes);

Laravel Eloquent Save to DB Using Create - Unhelpful Error

I get a very unhelpful error when I try and insert a new record in to my db. Does anyone have any idea where to start to solve this error?
user_id
That's all it says. (This is the name of one of my required fields in the table I'm saving to but it's not very descriptive.)
For reference here's my code:
$data = array(
'user_id'=>1,
'post_type'=>'0',
'post_title'=>'blah',
'description'=>'blah');
//it fails on this line
$id = Post::create($data);
Here's what my model looks like:
class Post extends Eloquent{
public static $rules = array(
'user_id'=>'required',
'post_type'=>'required',
'post_title' => 'required|max:25',
'description'=>'required'
);
public static function validate($data){
return Validator::make($data, static::$rules);
}
public function user(){
return $this->hasOne('User', 'id', 'user_id');
}
}
Tried getting rid of all relationships and validation in the model. That didn't work.
This is called mass-assignment in Laravel, what you need to do to get it working on your model is to set a protected array called $guarded to be empty. Add this to your model.
protected $guarded = array();
What this array does, it can prevent attributes to be mass-assigned with an array, if you don't want an attribute to be filled with the Model::create() method, then you need to specify that attribute in the $guarded array.
If instead you want to specify only the fillable attributes, Laravel's Eloquent also provides an array called $fillable where you specify only the attributes that you want to fill via the mass-assigment way.
Further reading:
Mass Assignment:
http://laravel.com/docs/eloquent#mass-assignment
Create Method:
http://laravel.com/docs/eloquent#insert-update-delete

Categories