samedi 17 octobre 2015

Laravel model method with default value

There are two tables

  • products
  • pictures ( has product_id , priority)

in my Product model i can get all pictures with:

public function pictures(){
    return $this->hasMany('App\Picture');
}

Now i want to create a function to get the main pictures url (lowest priority value with product_id of picture), and if there is no result return a default value. I tried:

public function mainpicture(){
    $picture = $this->pictures()->orderBy('priority','desc')->first();
    if($picture == null)
        return 'default/default.png';
    return $picture->url;
}

This gives the error:

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

When returning a value it's never of the type Illuminate\Database\Eloquent\Relations\Relation but just an url. How can I make a method to get the mainpicture or a default value?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1OAIbCE
via IFTTT

Aucun commentaire:

Enregistrer un commentaire