I have a query that fetches comments of posts. It returns this error when a particular post has no comments. Below is my query.
$comments=PostComments::with('user:id,username')
->where('post_id',$this->id)->latest()->get();
This is my Comments model
protected $table = "post_comments";
protected $fillable = ['comment','post_id','user_id'];
protected $hidden = ["updated_at","laravel_through_key","post_id"];
// Carbon instance fields
protected $dates = ['created_at', 'updated_at'];
public function user(){
return $this->hasMany(User::class,'id','user_id')->latest();
Your $this must be null. You could show a screenshot of the error where it will show you the line where the error occurred, which would make debugging it easier.
Related
i can't figure out why my eloquent relationship is not working.
I have the grid and details tables related (es. grid.id = details.order_id). This works for first 2 tables but not for other 2 that are almost a copy of the first.
Working relationship code :
OrderGrid model:
use HasFactory;
protected $table = 'orders_grid';
protected $fillable = [
'user_id',
// more data
];
public function order_detail()
{
return $this->hasMany('App\Models\OrderDetail');
}
OrderDetail model:
use HasFactory;
protected $table = 'orders_detail';
protected $fillable = [
'order_id',
// more data
];
public function order_grid()
{
return $this->belongsTo('App\Models\OrderGrid', 'order_id', 'id');
}
In controller
$data_details = OrderDetail::where('order_id', $id)->get();
in view
$data_details->first()->order_grid->id
// so i can get the ID from the related table
Now i have two more very similar models which relations are not working:
OrderGrid model 2
use HasFactory;
protected $table = 'orders_grid_jde';
protected $fillable = [
'total_order',
// more data
];
public function detail_jde()
{
return $this->hasMany('App\Models\OrderDetailJde');
}
OrderDetail model 2 :
use HasFactory;
protected $table = 'orders_detail_jde';
protected $fillable = [
'order_jde_id',
];
public function grid_jde()
{
return $this->belongsTo('App\Models\OrderGridJde', 'order_jde_id', 'id');
}
In controller:
$data_details = OrderDetailJde::where('order_jde_id', $id)->get();
In view:
$data_details->first()->order_jde_id->id
This is not working, if i dump($data_details->first()) relations is empty array, not as in the screen shown before
Another weird behaviour on working relation: if i dump $data_details->first() in the controller i don't see the relation, but if i do it in view it shows as in the screen.
Sorry for the long post, tried to be understandble as possible
In your Controller call the relation like this:
$data_details = OrderDetailJde::where('order_jde_id', $id)->with("grid_jde")->get();
In view:
$data_details->first()
It will give all the detils.
It should work now.
In the view where you have the error, you are accessing the directly to the field named order_jde_id instead of the relationship grid_jde.
Tips:
You should eager load the relationships if you are planning to use these in the view.
$books = Book::with('author')->get();
https://laravel.com/docs/9.x/eloquent-relationships#eager-loading
im still newbie, and trying to save data from REAXML file.
vendor for parsing REAXML from https://github.com/i4ucode/reaxml
Route:
Route::get('/admin/synctest', 'Admin\\AdminController#synctest');
Model Property
class Property extends Model
{
protected $table = 'properties';
protected $primaryKey = 'id';
protected $fillable = ['refID', 'propkind_id', 'other column'];
public function Kind()
{
return Propkind::findOrfail($this->propkind_id)->name;
}
//other public function
}
Model Propkind
class Propkind extends Model
{
protected $table = 'propkinds';
protected $primaryKey = 'id';
protected $fillable = ['id', 'name', 'slug'];
public function Property(){
return $this->hasMany('App\Property');
}
//other public function
}
Controller
public function synctest()
{
// get new class
$processor = new \REA\XmlProcessor();
$directories = Storage::disk('reaxml')->files();
foreach ($directories as $zipFile) {
//get XML file
$files = file_get_contents(url('feed/' . $zipFile));
//process the xml
$properties = $processor->parseXmlString($files);
//loop
foreach ($properties as $property) {
Property::updateOrCreate(
['refID' => $property->getRefID()],
[
//other code
'propkind_id' => Propkind::where('name', $property->getCategoryNaskleng())->first()->id, ===> ErrorException (E_NOTICE) Trying to get property of non-object
]
);
}
}
}
this piece of code Propkind::where('name', $property->getCategoryNaskleng())->first()->id)
==>show data but trow
ErrorException Trying to get property of non-object.
some kind of enlightenment, wisdom, very appreciate.
the difference between dd() and dump() is that dd() stops the execution of the script (die), dump() shows a representation of the argument but it doesn't stop the script.
for this reason I guess that the error (notice) comes after the excution of this piece of code you have posted.
clearly one of the values of $properties doesn't return a model
after several hours i found that null is the problem.
thank you #Devon for insight. #simonecosci and #Leena Patel for your comment.
I have hundreds of fields in my table and I dont want to write all the field in the$fillablearray. Is there any way tobypass $fillable process` ?
class MyClass extends Eloquent {
protected $fillable = array('firstField', 'secondField',.......);
}
You could do it the opposite way:
Specify the guarded attributes (all fields that should not be fillable).
protected $guarded = array('id', 'created_at', '...');
And remove the $fillable completely.
I'm building some API app using Slim3 and Eloquent as ORM for model, and having some strange issue.
When I save model, I get internal server error, and can't catch error at all.
My model have only two columns, id pk autoincrement and name (string 255)
this is my settup:
Model:
class Version extends Illuminate\Database\Eloquent\Model
{
protected $table = 'version';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name'];
protected $hidden = ['id'];
}
Action:
public function create(RequestInterface $request, ResponseInterface $response)
{
$params = $request->getParsedBody();
$class = $this->model; //fully namespaced class name
$model = new $class();
$model->fill($params);
return $model->save() ?
$this->success($response, "{$this->getModelName()} successfully saved.") :
$this->error($response, $model->errors());
}
I manager to localize issue to this part of code in Illuminate\Database\Eloquent\Builderline #1242
if (in_array($method, $this->passthru)) {
return call_user_func_array([$this->toBase(), $method], $parameters);
}
But I have no idea what is wrong
EDIT:
I'm using PHP/7.0.0-dev and Slim 3.1
Is Eloquent PHP 7 compatible?
Your Model is a Eloquent Model so to create you can use following code
$version = App\Version::create(['name' => 'Your version name']);
This will remove all the unnecessary functions, and keept yuor code clean.
In your case make sure the $request->getParsedBody();
returns the correct format for Eloquent to use it.
My EloquentUserRepository (concrete implementation) has some methods like getCompanies($userId) and getProfile($userId), for example.
In both cases, before returning stuff, they fetch the user, like so:
$user = User::find($userId);
So, when I need to call those two methods in the same request, the data is fetched twice.
Am I missing something or am I using repositories wrongly?
What if you approached it from the relationship side instead? I'm assuming that Companies live in a different table. So could you acquire the companies with something like this?
<?php
class User extends Model {
protected $table = 'users';
protected $fillable = ['name', 'email', 'avatar'];
protected $hidden = ['password', 'remember_token'];
public function companies()
{
return $this->hasMany('App\Company', 'user_id');
}
}
Then you could find the companies with:
$user = User::find($userId)->load('companies')->get();
and you'd already have the companies loaded.
If the profile is in a different table you could do a similar relationship, like this:
<?php
class User extends Model {
protected $table = 'users';
protected $fillable = ['name', 'email', 'avatar'];
protected $hidden = ['password', 'remember_token'];
public function profile()
{
return $this->hasOne('App\Profile', 'user_id');
}
}
I'm not certain if this is exactly what you are looking for, but it's the approach I like to use when finding items that are related to a particular model.