A
A
Anon33632020-07-14 22:21:30
Laravel
Anon3363, 2020-07-14 22:21:30

How to get from the database Products that the user added to the Wishlist?

public function WishlistPage(){
    $my_id = Session::get('id');
    $wish = [];
    $product = [];
    $myWishlist = Wishlist::where("user_id",$my_id)->get('product_id');
    // dd($myWishlist);
    foreach($myWishlist as $item){
      $id = $item['product_id'];
      array_push($wish,$id);
      $productsW = Products::where('id','=',$item['product_id'])->get();
      return view('/wishlist')
      ->with('myWish',$productsW)
      ->with('photo');
    }


Here is the Products
5f0e0580c459a306380520.png

Here is the Wishlist of Users
5f0e05a9eb88a977643762.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2020-07-14
@Sanasol

To get started, it’s probably worth going to the documentation section about relationships.
https://laravel.com/docs/master/eloquent-relationships
And then forget forever that you can make queries to the database in a cycle, or at least until the moment when you know exactly what is needed and what will result.
You can also install an IDE and format the code. See that return in the loop is also done.
In general, everything is wrong here, even at the level of syntax.

public function WishlistPage()
{
    $my_id = Auth::id();
    $myWishlist = Wishlist::with('product')->where("user_id",$my_id)->get();
    return view('/wishlist')
      ->with('wishes', $myWishlist)
      ->with('photo');
}

public function WishlistPage()
{
    $user = Auth::user();
    $myWishlist = $user->wishlist()->with('product')->get();
    return view('/wishlist')
      ->with('wishes', $myWishlist)
      ->with('photo');
}

public function WishlistPage()
{
    $user = Auth::user();
    $products = [];
    $myWishlist = $user->wishlist()->with('product')->get();
    foreach($myWishlist as $wish) {
        $products[] = $wish->product;
    }
    return view('/wishlist')
      ->with('products', $products)
      ->with('photo');
}

Many options in general, but all rest on the relationship one way or another in the normal version. Otherwise what for then ORM, Model, Laravel and that's it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question