php - Return relation if it counts greater than 0 else return other relation
Get the solution ↓↓↓I want to return a relation if it has results greater than 0 otherwise it should return other relation
public function default_product_image()
{
if(count($this->ztecpc_product_images()->get()) > 0)
{
return $this->hasMany('App\ZtecpcProductImage','product_id','id')//if count > 0 then return this relation
->select('id','product_id','image');
}
return $this->hasOne('App\ProductImagesModel','product_id','id')//else return this relation
->where('main_image',1)
->select('id','product_id','image');
}
public function ztecpc_product_images()
{
return $this->hasMany('App\ZtecpcProductImage','product_id','id')
->select('id','product_id','image');
}
I want to returnreturn $this->hasMany('App\ZtecpcProductImage','product_id','id')
->select('id','product_id','image');
ifztecpc_product_images
relation has the results greater than 0 otherwise it should return other relation in the function. My problem is that it is always return empty array which I guess it the if-conditionif(count($this->ztecpc_product_images()->get()) > 0)
is always true.
Answer
Solution:
Change your if statement like that:
if($this->ztecpc_product_images()->count() > 0)
Answer
Solution:
I think your guess is correct and I believe I know why:
$this->ztecpc_product_images
Will return an Eloquent Collection rather than an array. This is an object and will always return true even if empty.
Try replacing it with the following:
if ($this->ztecpc_product_images->isNotEmpty()) {
...
}
This uses the available Eloquent Collection methods to check for a lack of results.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: cannot access offset of type string on string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.