Laravel exception: Creating default object from empty value - laravel

I'm getting this error just by instantiating a Model and setting a property.
$order_datail = new OrderDetail;
$order_detail->quantity = $product['quantity'];
I'm searching for hours for the cause of this problem but can't find it.
The constructor of OrderDetail is executed. table is order_details, but even by setting protected $table = 'order_details', I'm still getting this error. And yes there is a column 'quantity' in this table.
Strange thing is that I've no problem with other models.
$order = new Order;
$order->pickup_date = $request['date'];
$order->pickup_time = $request['pickupTime'];
The above code runs fine.
Model OrderDetail:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class OrderDetail extends Model
{
use SoftDeletes;
public function replaceds()
{
return $this->hasMany('App\Models\Replaced');
}
public function orders()
{
return $this->belongsTo('App\Models\Order');
}
public function products()
{
return $this->hasMany('App\Models\Product');
}
public function collis()
{
return $this->hasMany('App\Models\Colli');
}
}
Anyone that knows what can be the cause of this?

There is a spelling error on $order_datail = new OrderDetail;
Change it to: $order_detail = new OrderDetail;

Related

Laravel8.x - Getting exception while accessing belongsTo relationship

I have a model class created in my laravel 8.x application with the code as given below
class City extends Model
{
use HasFactory;
protected $table = 'portal_cities';
public function belongsTo()
{
return $this->belongsTo(State::class); // also tried giving 'state_id' as second parameter
}
}
I have the portal_cities table as below
When i am trying to access the following code
$eventobj = App\Models\Event::find(1);
echo $eventobj->location->city->name;
It is giving the following error
Declaration of App\Models\City::belongsTo() should be compatible with Illuminate\Database\Eloquent\Model::belongsTo($related, $foreignKey = NULL, $ownerKey = NULL, $relation = NULL)
Can you please tell me what is causing the error and what can be done to rectify it?
change relation method name
for example:
public function state()
{
return $this->belongsTo(State::class); // also tried giving 'state_id' as second parameter
}
you can't create belongsTo() function as it is core function in model
so you need to change this
class City extends Model
{
use HasFactory;
protected $table = 'portal_cities';
public function state() // change this name
{
return $this->belongsTo(State::class);
}
}
you can check core function here
https://github.com/laravel/framework/blob/8.x/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php#L193

Cannot establish relationship between two tables in Laravel

I want to create a relation between lising and attribute table in laravel for that i have used following code to establish relationship between them but the data in my view is not coming from both the tables. I'm getting following error:
Call to undefined relationship [adListAttributes] on model
[App\Models\AdListing].
Here listing can have as many attribute associated with and attributes
can be associated to many listings
ad_listings:
id
title
name
date
ad_list_attributes table :
id
listing_id
name
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListAttribute extends Model
{
protected $table = "ad_list_attributes";
public function Listings()
{
return $this->belongsToMany('AdListing', 'id', 'listing_id');
}
}
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListing extends Model
{
protected $table = "ad_listings";
public function Attributes()
{
return $this->belongsToMany('AdListAttribute', 'listing_id', 'id');
}
}
Problem is that you are using belongsToMany in both the models.This will cause a problem.
In AdListAttribute model,
public function listing_information()
{
return $this->belongsTo('App\AdListing', 'id', 'listing_id');
}
In AdListing model,
public function adlisting_attributes()
{
return $this->hasMany('App\AdListAttribute', 'listing_id', 'id');
}
You can get the results using,
$response = AdListing::get();
if($response->adlisting_attributes)
{
foreach($response->adlisting_attributes as $attribute)
{
echo $attribute->name;
}
}
Problem is that ur not calling the relationship with the right name i assume
$listings = AdListing::with('Attributes')->get();
Update :
Try this :
use App\Models\AdListAttribute;
//
return $this->belongsToMany(AdListAttribute::class, 'listing_id', 'id');
Same for other model, then try

Eloquent one to many relationship not working

I'm stuck for hours with one of those issues where a fresh set of eyes might help. I just can't understand what's missing.
I'm connecting a model called User_ativo and defining two one-to-many relations to models Instituicao and Tipo_Ativo.
My database is simple.
Table user_ativo has columns "tipo_ativo_id" and "instituicao_id". I have a test row where both are set to 1. Both my tables instituicoes and tipo_ativos have only "id" and a string field "nome" (name). Both have a record with id == 1.
User_ativo.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User_ativo extends Model
{
public function tipo(){
return $this->belongsTo('App\Tipo_ativo');
}
public function instituicao(){
return $this->belongsTo('App\Instituicao');
}
}
Instituicao.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Instituicao extends Model
{
protected $table = 'instituicoes';
public function user_ativos(){
return $this->hasMany('App\User_ativo');
}
}
Tipo_ativo.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tipo_ativo extends Model
{
protected $table = 'tipo_ativos';
public function user_ativos(){
return $this->hasMany('App\User_ativo');
}
}
My controller method that fetches the date goes as follow:
public function index()
{
$ativos = User_ativo::with('tipo', 'instituicao')->get();
return view('ativos.index', compact('ativos'));
}
Now here's where it gets interesting, for some reason I can't figure out, when I echo the $ativos variable in my view I get this:
[{"id":1,"user_id":1,"instituicao_id":1,"tipo_ativo_id":1,"tipo":null,"instituicao":{"id":1,"nome":"Banco do Brasil"}}]
So, weirdly my relationship with the Instituicao model works, but the one with Tipo_ativo returns null.
I'm pretty confident someone will point out some dumb and obvious mistake in all of this, but I can't for the life of me understand why one works and the other doesn't since they're pretty much the same thing.
Your relationships names are not according to laravel convention.
Read below function and provide foreign_key and local_key/owner_key to your relationships then it will work
public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null){}
If we do not follow laravel convention while creating relationships then we have to tell it that these are the foreign and local keys that should be used.
Read more here
class User_ativo extends Model{
public function tipo(){
return $this->belongsTo('App\Tipo_ativo','user_ativo_id'); //second parameter is foreign_key_of_User_avito_table_here
}
public function instituicao(){
return $this->belongsTo('App\Instituicao','user_ativo_id'); //second parameter is foreign_key_of_User_avito_table_here
}
}
class Instituicao extends Model
{
protected $table = 'instituicoes';
public function user_ativos(){
return $this->hasMany('App\User_ativo','instituicao_id'); //second parameter is foreign key of Instituicao model
}
}
class Tipo_ativo extends Model
{
protected $table = 'tipo_ativos';
public function user_ativos(){
return $this->hasMany('App\User_ativo','tipo_ativo_id'); //second parameter is foreign key of Tipo_ativo model.
}
}

Call to undefined method Illuminate\Database\Query\Builder::save() on seed

I'm trying to create seeders to my models using seed and factory. My models have relationship one to many. When I run
php artisan db:seed --class=ChildTableSeeder
I get the following error:
In Builder.php line 2461:
Call to undefined method Illuminate\Database\Query\Builder::save()
Independently of the error the data seed is added to the target table.
My table's structure is like follow:
parents
- parentId
- name
- value
childs
- childId
- parentId
- views
- count
And my models:
//Parent.php
<?php
namespace App\Models\Api;
use Illuminate\Database\Eloquent\Model;
class Parent extends Model
{
protected $primaryKey = 'parentId';
public $incrementing = false;
protected $keyType = 'string';
}
//Child.php
<?php
namespace App\Models\Api;
use Illuminate\Database\Eloquent\Model;
class Child extends Model
{
protected $primaryKey = 'childId';
public $incrementing = false;
protected $keyType = 'string';
public function parents()
{
return $this->belongsTo('App\Models\Api\Parent', 'parentId', 'parentId');
}
}
Also see the Seed code
//ParentTableSeeder
factory(App\Models\Api\Child::class, 50)->create()->each(function ($u) {
$u->parents()->save(factory(App\Models\Api\Parent::class)->make());
});
Anyone has an idea what I'm doing wrong? or How to solve this issue?
You need to use associate() function insted of save()
Also parents() relationshiop's definition is wrong
public function parents()
{
return $this->belongsTo('App\Models\Api\Parent', 'parentId', 'childId');
}
Use the associate method instead of save when creating the relationship:
$p = factory(App\Models\Api\Parent::class)->create():
$u->parents()->associate($p);
$u->save();

Custom attribute crashing on toJSON

I am trying to determine which position the order is in to generate a order id, but this crashes laravel, nothing in the logs, just a 500 error in the browser:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Load extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $guarded = ['id', 'created_at', 'updated_at'];
protected $appends = ['order_no'];
public function workorder()
{
return $this->belongsTo('App\WorkOrder', 'work_order_id');
}
public function getOrderNoAttribute()
{
$count = 1;
foreach ($this->workorder->loads as $load) {
if ($load->id == $this->id) {
break;
}
$count++;
}
return $this->workorder->id . "-" . $count;
}
}
When I changed it to return just an integer it worked, so I am almost certain it is the relation access causing the issue. Is there a way to do this that is better?
Generally while defining calculated attributes, dependence on relationship should be avoided. So one way to achieve what you are trying is (as you mentioned solved) is to get all loads having the same work_orderid and proceed with it.
public function getLoadCountAttribute ()
{
$id = $this->work_order_id;
return static::where('work_order_id', $id)->count();
}
Another way, more logical I guess, would be to define a relationship and eager load
//define a relation in your Load model
public function load_count ()
{
return count($this->workorder->loads)
//-1 if you want to exclude the current load from count
;
}
//Then use Load::with('load_count') to eager load the load_count
//You may also use global scope
Yet another way would be to define a static function on Workorder model, which will accept an id and return the load_count
//Workorder model
public static function getLoadCount($id)
{
$workorder = static::findOrFail($id);
return count($workorder->loads);
}
Hope this helps.

Resources