Pergunta

I am looking for solution how to access eloquent model items by 'alias' field. There is no problem accessing items by 'id'. But building a custom query I find myself unable to access item properties.

This piece of code works perfect

$cat = Category::find(1);
return $cat->title;

But if I am querying items with any other argument - properties are inaccessible

This code

$cat = Category::where('alias','=','vodosnab')->get();
return $cat->title;

throws an exception

Undefined property: Illuminate\Database\Eloquent\Collection::$title

Could you please help.

Foi útil?

Solução

You already got the answer but here are some insights, when you use get() or all(), it returns a collection of model objects, which is an instance of Illuminate\Database\Eloquent\Collection, so here you'll get a Collection object

$cat = Category::where('alias','=','vodosnab')->get();

Now, you can use, $cat->first() to get the first item (Category Model) from the collection and you may also use $cat->last() to get the last item or $cat->get(1) to get the second item from the collection. These methods are available in the Collection object.

Using the first() method like Category::where('alias','=','vodosnab')->first(); will return you only a single (the first mathing item) model which is an instance of your Category model. So, use all() or get() to get a collection of model objects and you can loop through the collection like:

foreach(Category::all() as $cat) { // or Category::get()
    $cat->propertyName;
}

Or you may use:

$categories = Category::where('alias','=','vodosnab')->get();
foreach($categories as $category) {
    $category->propertyName;
}

Also, you may use:

$categories = Category::where('alias','=','vodosnab')->get();
$firstModel = $categories->first();
$lastModel = $categories->last();
$thirdModel = $categories->get(2); // 0 is first

If you need to get only one then you may directly use:

$category = Category::where('alias','=','vodosnab')->first();
$category->fieldname;

Remember that, if you use get() you'll get a collection of Model objects even if there is only one record available in the database. So, in your example here:

$cat = Category::where('alias','=','vodosnab')->get();
return $cat->title;

You are trying to get a property from the Collection object and if you want you may use:

$cat = Category::where('alias','=','vodosnab')->get();
return $cat->first()->title; // first item/Category model's title
return $cat->last()->title; // last item/Category model's title
return $cat->get(0)->title; // first item/Category model's title

You may read this article written on Laravel's Collection object.

Outras dicas

get() returns a Collection of items. You probably need first() that returns a single item.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top