Carol.Kar
Carol.Kar

Reputation: 5355

Get attribute from selected model

I am using PHP 7.1.33 and Laravel Framework 5.8.36.

I am getting a model back by name like the following Product::where('name', '=', $name)->get();

My Product model looks like the following:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'product';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'url', 'category'];
}

When trying to get an attribute like the following I get an error:

$product = Product::where('name', '=', $name)->get();
$product->$url; // ERROR
$product->$category; // ERROR

Any suggestions how to access the attributes on my retrieved model?

I appreciate your replies!

Upvotes: 0

Views: 50

Answers (3)

Ramin eghbalian
Ramin eghbalian

Reputation: 2667

try this:

$product = Product::whereName($name)->first();
$product->$url;
$product->$category;

Upvotes: 2

Hamelraj
Hamelraj

Reputation: 4826

from your query you will get many collection of data so you have to access like this

$products = Product::where('name', '=', $name)->get();

foreach($products as $product){
  dd($product->$url,$product->$category);
}

but i think you if you have one data for particular name use first()

$product = Product::where('name', '=', $name)->first();
dd($product->$url,$product->$category);

Upvotes: 1

Tim Lewis
Tim Lewis

Reputation: 29288

Don't use get() if you only expect a single Model instance. ->get() returns a Collection, and you can't access a single property without looping.

Use ->first(), or a similar method like firstOrFail(), find(), findOrFail(), etc.:

$product = Product::where('name', '=', $name)->first();
$product->$url;
$product->$category;

If you're expecting multiple instances, then you may use ->get() in conjunction with a loop:

$products = Product::where('name', '=', $name)->get();
foreach($products AS $products){
  $product->$url;
  $product->$category;
}

Upvotes: 2

Related Questions