hyphen
hyphen

Reputation: 3440

Laravel Get method return value for each related model

I have a Client model that has a hasMany relationship to a Location model. In my Location model I have a status() method that returns an array.

In my ClientController, I'm getting the client model, and then getting all related Locations, but I also want to include the array returned from the status method attached to each location. I'm unsure of how to do this. I'm sure I can do it by just using a foreach loop over each location, but I'm wondering if there's an "eloquent" way of doing it.

Here is my ClientController:

    public function show($id)
    {
        $client = Client::findOrFail($id);        
        
        $locations = $client->locations()->withTrashed()->get();

        //foreach($locations as $location)
        //{
         //   print_r($location->status());
        //}


        return view('pages.clients.show')
            ->with('client', $client)
            ->with('locations', $locations)
    }

Here's my Location Model method:

    public function status()
    {
        $result = array();

        if($this->deleted_at)
        {
           $result['color'] = 'danger';
           $result['value'] = 'Inactive';
        }
        elseif($this->is_onboarding_completed)
        {
            $result['color'] = 'success';
            $result['value'] = 'Active';
        }
        else
        {
            $result['color'] = 'warning';
            $result['value'] = 'Onboarding';
        }

        return $result;
    }

My Location relationship:

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

My Client relationship:

    public function locations()
    {
       return $this->hasMany(Location::class);
    }

Also, I'd like to know if/how I can return the status automatically with the location whenever it's returned. I know I can do this with locations using protected $with = [];, but I get an error when I tried to include a non-relationship.

Also, any design improvements welcome, if there's a better way to do this.

Upvotes: 0

Views: 1045

Answers (1)

W Kristianto
W Kristianto

Reputation: 9303

As @lagbox said in the comment box, you need an accessor.

Location model :

public function getStatusAttribute()
{
    $result = [];

    if($this->deleted_at)
    {
        $result['color'] = 'danger';
        $result['value'] = 'Inactive';
    }
    elseif($this->is_onboarding_completed)
    {
        $result['color'] = 'success';
        $result['value'] = 'Active';
    }
    else
    {
        $result['color'] = 'warning';
        $result['value'] = 'Onboarding';
    }

    return $result;
}

Controller :

public function show($id)
{
    $client = Client::findOrFail($id);        
    $locations = $client->locations()->withTrashed()->get();

    foreach($locations as $location)
    {
       dd($location->status);
    }

    ...
}

Upvotes: 1

Related Questions