M
M
mrdragon90002019-03-03 16:28:50
Laravel
mrdragon9000, 2019-03-03 16:28:50

How, when receiving all instances of the model, immediately load whether they belong to the current user?

There is a User and Product model. Users can have many of the same products(many to many), but each product is not more than once.
It is necessary to show a list of all products available on the site in your account, but if the product has already been purchased by this user, this should be immediately indicated.
How to do it in the most efficient way?
In general, tell me an alternative to Product::all() so that marks are also loaded, whether the product was purchased by the current user.
I don’t really want to hack and do Product::all() and $user->products() , and then splice the results. Can you do without it?)

Answer the question

In order to leave comments, you need to log in

5 answer(s)
J
jazzus, 2019-03-03
@mrdragon9000

if I understand the task correctly, in the User model

public function getProductById($id)
{
  return $this->products()->find($id);
}
      
public function hasProduct($id)
{
    return $this->getProductById($id)->count()>0;
}

in controller
if ($user->hasProduct($product->id)) {
     // не продавать
}

pattern
@if ($user->hasProduct($product->id))
 <div class="danger">
      Вы уже купили этот товар
  </div>
@endif

you need to check what i wrote

A
Anton Shelestov, 2019-03-03
@ShelestovAnt

There is no place to check, but it might work like this:

Product::with([
            'user' => function($query) {
                return $query->where('user_id', \Sentinel::getUser()->id);
            }
        ])->get();

If user is not empty, it means purchased by the current user

R
Roman, 2019-03-03
@procode

And why crutch something?
You get two collections, subtract one from the other in a loop or something else, and output depending on.
This is the simplest solution.

D
Dmitry, 2016-10-15
@alexandrvarantsov

Good evening.
Why produce the same questions?
This is the third one in a row with the same problem.
Reinstall the entire system if you do not have enough knowledge how to restore everything.
Reinstallation will take much less time than writing your questions here.
Reinstall, and remember that ubuntu and others like it are not windows.
It is difficult to kill the system, but all the same, you have to think about what and where to enter and where to press.

Z
zooks, 2016-10-15
@zooks

Ну так поставьте Python. Нет дисковода, но всегда есть USB - можете переустановить с загрузочной флешки.
Если выберете путь переустановки, то имеет смысл перейти на Ubuntu 16.04.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question