Laravel 4.2 Eloquent create: Array to string conversion error - php

I'm using Laravel 4.2.* I have a User Model where insert() method is working normally but when I'm using create() method it is throwing an error:
Array to string conversion
My model:
class User extends Eloquent{
public $table = 'users';
protected $primaryKey = 'user_id';
protected $fillable = ['first_name', 'last_name', 'created_by'];
public function insertUserInfo($data)
{
//return self::insert($data); //working with no error but not adding `created_at`
return self::create($data); //Array to string conversion
}
}
Sample data:
$data = [
'first_name' => 'Jhon',
'last_name' => 'Doe',
'created_by' => Auth::id() // var_dump(Auth::id()) => int(11)
];
It 'll be helpful if anyone can help me as why create() is throwing an error.
PHP v5.6.3
EDITED
I can assure that there is no array value inside $data. and the same $data is working with insert() but throwing error when using create() or save() method.

Add array type hinting:
public function insertUserInfo(array $data)
{
return self::create($data);
}

Related

Return default value if belongTo relation is returned null

I have a belongTo relation, if join condition is matched then ok but when there is no data for this it returns null. In this case, I want it returns default value as I expected. This is what I try but it not success. Please help me?
class Task extends Model
{
use SoftDeletes;
protected $table = 'tasks';
protected $fillable = [
'name',
'description',
'project_id',
];
protected $with = ['project', 'status'];
// this is expected
public function getProjectAttribute($value)
{
return $value ?? ['id' => '', 'name' => ''];
}
/**
* #return App\Modules\Com\Models\Project
*/
public function project()
{
return $this->belongsTo(Project::class, 'project_id', 'id')->select(['id', 'name']);
}
}
With description attribute, I can override it but why I dont the same thing with project attribute? And how do I set where for project relation?
Like this Task::select(*)->project()->where('project.name', 'ABC');.
I've never used Laravel -- but... the documentation shows that you can set a default for belongsTo when using it for updating in order to avoid conditional checks. Perhaps it will work for selecting too.
You can try adding the default to the end of your call.
return $this->belongsTo(Project::class, 'project_id', 'id')
->select(['id', 'name'])
->withDefault([
'project_id' => 'project.name',
'id' => 'ABC',
]);
Source: https://laravel.com/docs/6.x/eloquent-relationships#default-models
or
You could do a conditional check:
public function project()
{
$return $this->belongsTo(Project::class, 'project_id', 'id')->select(['id', 'name']);
if( $return === null )
// return your default values
else
return $return;
}

Laravel mass-assignment doesnt insert boolean

I am trying to do the mass assignment with laravel like. But I have a field called 'hidden' that in the database is a TINYINT. From my front-end I get a boolean back. When I mass-assign with 'hidden' => TRUE the field in DB still is 0. When i convert it back to a integer ('hidden' => 1) then the field is saved as 1.
I did added 'hidden' to my $fillable.
P.S. When I try inserting it into DB directy with mysql with boolean value, it works.
Anyone know what is wrong?
EDIT: this is my code,
public function store(Request $request) {
class Group extends Model
{
use Notifiable;
const CREATED_AT = 'created';
const UPDATED_AT = 'updated';
protected $table = 'groups';
protected $casts = [
'hidden' => 'boolean',
];
protected $fillable = [
'hidden',
// etc
];
}
public function store(Request $request) {
$post = $request->all();
$group_id = Group::create($post);
}
Front-end is Vue project. So laravel is my API. And I do get a TRUE out of $post['hidden'].
You need to cast the boolean in the model:
class YourModel extends Model
{
protected $casts = [
'hidden' => 'boolean',
];
}
This will tell Laravel the you want the hidden column to be treated as boolean and values like 0 and 1 will be returned as true/false and true/false saved as 0/1.
You can read more in Laravel doc mutators.
Change the database type to Bool. If you want to do that with a migration you can do: $table->boolean(‘hidden’);

Laravel DD helper not executing inside each function

I'm currently trying to troubleshoot my way through duplicating an object with its appropriate relationships. I usually use Laravel's DD helper to see if I'm getting the right information, but in this instance, I don't think that it's being run when it hits the line in the method that gets executed.
Here's my controller method that's handling the duplication.
$copiedManagementSystem = $managementSystem->replicate();
$copiedManagementSystem->inspections->each(function($inspection) {
$copiedInspection = $copiedManagementSystem->inspections()->create([
'name' => $inspection->name,
'management_system_id' => $inspection->managementSystemId,
'pass_score' => $inspection->passScore,
'max_score' => $inspection->maxScore,
'order' => $inspection->order,
]);
dd($inspection); //I've placed the dd here but it doesn't work in any position, in any part of the each function.
$inspection->checks->each(function($check){
$copiedInspection->checks()->create([
'question' => $check->question,
'values' => $check->values,
'type' => $check->type,
'inspection_id' => $check->inspectionId,
'order' => $check->order,
]);
});
});
$copiedManagementSystem->save();
Here is the ManagementSystem's model with the inspections relationship
class ManagementSystem extends Model
{
protected $table = 'management_systems';
protected $fillable = ['name', 'description'];
public function inspections()
{
return $this->hasMany(Inspection::class);
}
}
This is the inspection's model with the relations
class Inspection extends Model
{
protected $table = 'inspections';
protected $casts = [
'order' => 'integer'
];
protected $fillable = [
'name',
'management_system_id',
'pass_score',
'max_score',
'order'
];
public function checks()
{
return $this->hasMany(Check::class);
}
public function managementSystem()
{
return $this->belongsTo(ManagementSystem::class);
}
}
And finally, here is the check model with its relations.
class Check extends Model
{
protected $table = 'checks';
protected $fillable = [
'question',
'values',
'type',
'inspection_id',
'order'
];
public function inspection()
{
return $this->belongsTo(Inspection::class);
}
public function answers()
{
return $this->hasMany(Answer::class);
}
}
I'd really appreciate any help :)
EDIT: So I've come across a strange occurrence. If I run the following:
dd($copiedManagementSystem->inspections->count();
It returns 0. But if I run:
dd($managementSystem->inspections->count());
It returns 12, which is the correct value.
Does anyone know why this happens? And if so, how can I fix the issue?
Thank you!
Since replicate() does not replicate the relations you could try something like this.
$copiedManagementSystem = $managementSystem->replicate()
foreach($managementSystem->inspections as $inspection) {
$copiedManagementSystem->inspections->attach($inspection->replicate())
}
It is pseudo code, if you want the original inspections linked remove the $inspection->replicate() call and just use $inspection
Same goes for any other relations $managementSystem might have.

ErrorException in 2b026073a4c3afa6c3599efffe5361a356c89d88.php line 63: Trying to get property of non-object (View: \index.blade.php)

model user
protected $table = "users";
protected $fillable = ['name', 'email', 'password' ];
protected $hidden = [
'password', 'remember_token',
];
public function solicitud(){
return $this->hasMany('App\solicitud');
}
Model tiposolicitud
protected $table = "tiposolicitud";
protected $fillable = ['nombre'];
public function solicitud(){
return $this->hasMany('App\solicitud');
}
Model solicitud ( principal )
protected $table = "solicitud";
protected $fillable = [..extract... 'tiposolicitud_id','users_id'....];
public function tiposolicitud(){
return $this->belongsTo('App\tiposolicitud');
}
public function User(){
return $this->belongsTo('App\User');
}
Controller ( extract)
use App\solicitud as VarModel;
use App\User;
use App\tiposolicitud ;
...
public function index()
{
$var1 = VarModel::all();
return view('private.solicitud.index',compact('var1'));
}
index.php
#foreach ($var1 as $var)
<tr>
<td>{{$var->id}}</td> // OK
<td>{{$var->user->name}}</td> //NOT OK
<td>{{$var->tiposolicitud}}</td> // OK
Trying to get property of non-object (View: C:\wamp64\www\issdgr\resources\views\private\solicitud\index.blade.php)
I have problem with app / user
I have persisted the id of the user but I can not find the name ..
HELP!!!!!
The error is on your blade view with the following statement:
$var->id
I think its a multi-dimension Std Class Object. So before iterating, put a print_r() to check the content of it.
And one more thing, laravel maintain cache of all views inside
your_project/storage/framework/views
with name like 2b026073a4c3afa6c3599efffe5361a356c89d88.php that's why it is showing error here.

Laravel save many-to-many relationship in Eloquent mutators

I've got 2 models with a many-to-many relationship. I want to be able to set a specific attribute with an array of ids and make the relationship in the mutator like this:
<?php
class Profile extends Eloquent {
protected $fillable = [ 'name', 'photo', 'tags' ];
protected $appends = [ 'tags' ];
public function getTagsAttribute()
{
$tag_ids = [];
$tags = $this->tags()->get([ 'tag_id' ]);
foreach ($tags as $tag) {
$tag_ids[] = $tag->tag_id;
}
return $tag_ids;
}
public function setTagsAttribute($tag_ids)
{
foreach ($tag_ids as $tag_id) {
$this->tags()->attach($tag_id);
}
}
public function tags()
{
return $this->belongsToMany('Tag');
}
}
<?php
class Tag extends Eloquent {
protected $fillable = [ 'title' ];
protected $appends = [ 'profiles' ];
public function getProfilesAttribute()
{
$profile_ids = [];
$profiles = $this->profiles()->get([ 'profile_id' ]);
foreach ($profiles as $profile) {
$profile_ids[] = $profile->profile_id;
}
return $profile_ids;
}
public function profiles()
{
return $this->belongsToMany('Profile');
}
}
However the setTagsAttribute function isn't working as expected. I'm getting the following error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'profile_id' cannot be null (SQL: insert intoprofile_tag(profile_id,tag_id) values (?, ?)) (Bindings: array ( 0 => NULL, 1 => 1, ))
You can't attach many-to-many relations until you've saved the model. Call save() on the model before setting $model->tags and you should be OK. The reason for this is that the model needs to have an ID that Laravel can put in the pivot table, which needs the ID of both models.
It looks like you're calling the function incorrectly or from an uninitialized model. The error says that profile_id is NULL. So if you're calling the function as $profile->setTagsAttribute() you need to make sure that $profile is initialized in the database with an ID.
$profile = new Profile;
//will fail because $profile->id is NULL
//INSERT: profile->save() or Profile::Create();
$profile->setTagsAttribute(array(1,2,3));
Additionally, you can pass an array to the attach function to attach multiple models at once, like so:
$this->tags()->attach($tag_ids);
You can also pass it the model instead of the ID (but pretty sure array of models won't work)
Try using the sync method:
class Profile extends Eloquent {
protected $fillable = [ 'name', 'photo', 'tags' ];
protected $appends = [ 'tags' ];
public function getTagsAttribute()
{
return $this->tags()->lists('tag_id');
}
public function setTagsAttribute($tag_ids)
{
$this->tags()->sync($tagIds, false);
// false tells sync not to remove tags whose id's you don't pass.
// remove it all together if that is desired.
}
public function tags()
{
return $this->belongsToMany('Tag');
}
}
Don't access the tags through the tags() function, rather use the tags property. Use the function name if you want to pop additional parameters onto the relationship query and the property if you just want to grab the tags. tags() works in your getter because you're using get() on the end.
public function setTagsAttribute($tagIds)
{
foreach ($tagIds as $tagId)
{
$this->tags->attach($tagId);
}
}

Categories