Home > Mobile >  Laravel - Use a column from a model relation
Laravel - Use a column from a model relation

Time:04-18

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 >
                                                Credit
                                            </span>
                                            @break
                                        @case($status_credits >= 2)
                                            <span >
                                                Credits
                                            </span>
                                            @break
                                        @default
                                            <span >
                                                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

CodePudding user response:

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()->...;

  • Related