Skip to content
Advertisement

Laravel – Use a column from a model relation

in my livewire view i get all the credits from their respective owners through the model relationship between clients and credits

Model: Client

protected $fillable = ['name'];

public function credits(){
    return $this->hasMany(Credit::class);
}
public function payments(){
    return $this->hasManyThrough(Payment::class, Credit::class);
}

Model: Credit

const ACTIVE= 1;
const LIQUIDATED= 2;

protected $fillable = ['amount', 'amount_end', 'status', 'dues'];

public function client(){
    return $this->belongsTo(Client::class);
}
public function provider(){
    return $this->belongsTo(Provider::class);
}
public function payments(){
    return $this->hasMany(Payment::class);
}

in my livewire view I have a foreach that gets me all the clients, inside a switch that counts the credits of the clients

Livewire: Show-client

@foreach ($clients as $item)
     ...
  @switch($item->credits->count())
                                        @case($status_credit = 1)
                                            <span class="px-2 py-1 inline-flex text-sm leading-5 font-semibold rounded-md bg-yellow-300 text-yellow-600 geosanslgbold text-md">
                                                Credit
                                            </span>
                                            @break
                                        @case($status_credits >= 2)
                                            <span class="px-2 py-1 inline-flex text-sm leading-5 font-semibold rounded-md bg-orange-300 text-orange-700 geosanslgbold text-md">
                                                Credits
                                            </span>
                                            @break
                                        @default
                                            <span class="px-2 py-1 inline-flex text-sm leading-5 font-semibold rounded-md bg-green-400 text-green-900 geosanslgbold text-md">
                                                Not Credits
                                            </span>
   @endswitch
 @endforeach

So far everything is fine, it tells me the credits and tells me if it has or not.

now the credits have the option to place them as active or liquidated

How would I make my switch, instead of telling me all the client’s credits, only take the active or in this case the ones with the number 1 and add the active credits

sorry for my bad english

Advertisement

Answer

I believe you are looking for what’s called “local query scopes” : https://laravel.com/docs/9.x/eloquent#local-scopes

    public function scopeIsLiquidated(Builder $query): Builder
    {
        return $query->where('status', LIQUIDATED);
    }

Usage :

$clients = ...->isLiquidated()->...;

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement