D
D
Dmitry Demidenko2018-10-18 10:50:25
Laravel
Dmitry Demidenko, 2018-10-18 10:50:25

Is it possible to select data like this?

Hello.
I often see such an implementation and wondered if such a practice is normal in Laravel.
For example, there is a variable obtained using the relation

// Переменная в контролере
$favorites = $user->favorites; // Получает все записи, которые пользователь добавил в избранное

// метод отношения в модели User
public function favorites(){
        return $this->hasMany('\App\Models\Favorite');
}

// К-во избранных исполнителей в представлении
Исполнители ({{ $favorites->where('performer_id', '<>', null)->count() }})

What interests me is whether it is normal to additionally call the where method in the view.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav, 2018-10-18
@detriat

No. At a minimum, count should be done in the controller. Better yet, use Laravel's Scope and write something like:

public function scopeHasPefrormer($query)
{
    return $query->where('performer_id', '<>', null);
}

The View is responsible for displaying the data, not looking for it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question