Laravel model object retrieving relation model with where condition without "get" method

- 1 answer

Ad

I'm working on octoberCMS(laravel framework), I have a doubt on retrieving relation model on where clause.

I have fetched a clothing_type record from "clothing type" model based on its primary key "id".

$clothing_type  = ClothingType::where('id',post('clothingtype_id'))->where('status','Active')->first();

This "clothing type" model is related with "products" model, the relation is => each clothing type hasMany products.

Every thing works fine; Now my business logic has two cases, one is to get all the products of the clothing type and another is to get the first product of the clothing type. So I have used the $clothing_type->products to get all the products and $clothing_type->products->first() to get the first product.

Now I have to apply a condition for both the cases. The condition is that only the product whose status is "Active" should be fetched, hence
$products = $clothing_type->products->where('status','Active'); and
$first_product_detail = $products->first();.

Every thing works as expected but how come the products are fetched without "get()" method. $clothing_type->products->where('status','Active')->get(); Since I'm new to relation I want to know how this works or is this a bad way to get records or improper assumption. But every thing works good.

$clothing_type  = ClothingType::where('id',post('clothingtype_id'))->where('status','Active')->first();
if(count($clothing_type->products))
{
    $products               = $clothing_type->products->where('status','Active');
    $first_product_detail   = $products->first();

}
Ad

Answer

Ad

You are doing it the correct way. When you access the relationship as an attribute Eloquent automatically retrieves the records.

However, if you access the relationship as a method, you get the query itself, to which you can add your filters:

if(count($clothing_type->products))
{
    $products               = $clothing_type->products()->where('status','Active')->get();
    $first_product_detail   = $products->first();
}

This would solve your problems

(documentation is over here (see the first item))

Edit: Also note that the first method is not a method of Eloquent, but from Collection, which is pretty powerful!

Edit2: I misread the part of your question where you want to know HOW this is possible. Both Eloquent and Collections have a where method. I assume you understand the working of the Eloquent one, but the one from Collection is pretty much the same (see documentation on the Collection where here)

I prefer the Eloquent one myself, because that limits the amount of records that is retrieved from the database. But if you need all the products (even the inactive ones) later on in your code, just use the Collection method to filter the active ones out

Ad
source: stackoverflow.com
Ad