Muhammad Ateek Muhammad Ateek - 10 months ago 40
PHP Question

show to pass predefined data from model to view in laravel

I have some predefined data in the form of array which I want to access into my views.
I'm using the following approach for this purpose.
I define a method in model, which returns an array.

//function in my model calss of cars.

public function colors(){
return ['white', 'blue','gray'];

When I call this method like that :


here is the code that i wants to use in my view file

@foreach($car->colors() as $color)
<p> {!!$color!!}</p>

It shows me the following error : Relationship method must return an object of type

What's the proper way to handle such type of situation if I want an array or any data from my model object or alternate way.

Answer Source

You could use Eloquent's accessors to add custom attribute to your model - see more details here:

In your case, the following should do the trick:

class Car extends Model {
  public function getColorsAttribute(){
    return ['white', 'blue','gray'];

Now you should be able to access the list of colors with:

foreach ($car->colors as $color) {

The error you're getting seems to be related to something else though - usually it means you're trying to eagerly load a non-existing relation. Make sure you don't have any calls to with('colors') on your Car model.