Search code examples
laravelhas-one

Retreive data with hasOne in Laravel 5.6


I would like to know how to retreive data with hasOne in laravel? For example, I have a brand table and a product table that has a column that contains the brand's id, so if a product should have a brand "hasOne" works perfectly with the relationship of the two tables, but how do I do if a product does not necessarily have a brand, then when adding the product the id of the brand stored in database is 0 and when I make a request on this line, laravel gives me an error.

Thanks for your answer.


Solution

  • When the product has no brand, instead of adding 0, enter NULL to the database. You will need to change the database and add ->nullable() to the brand_id column

    Also, it seems like a Product should belongTo a Brand instead of hasOne

    Your Product model should look like:

    class Product extends Model {
    
        public function brand() {
            return $this->belongsTo(Brand::class);
        }
    }
    

    And your Brand

    class Brand extends Model {
    
        public function products() {
            return $this->hasMany(Product::class);
        }
    }
    

    Then you can do the following:

    if($product->brand) {
        // product has brand
    }
    else {
        // product does not have brand
    }