Search code examples
phplaraveleloquentlaravel-5.8laravel-relations

How can I do this with Eloquent Relationship


I'm working on an Online Store project and I wanted to create Add To Favourite system for users to add products that they like to their favourite list.

So I have created a table named favourite_products which goes like this:

enter image description here

So the usr_id stands for user id and prd_id stands for product id.

Here is the User.php Model:

public function favourites()
    {
        return $this->belongsToMany(Product::class, 'favourite_products', 'usr_id', 'prd_id')->withTimestamps();
    }

And this the Product.php Model:

public function favouritees()
    {
        return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
    }

Now I wanted to get all the data from this table.

So I tried adding this to the Controller:

public function index()
    {
        $favouriteProducts = FavouriteProduct::all();
        return view('admin.shop.favourites.all', compact('favouriteProducts'));
    }

Then in the Blade:

@foreach($favouriteProducts as $fav_pro)
    @php
        $member_info = \App\User::where($fav_pro->usr_id)->first();
        $product_info = \App\Shop\Product::find($fav_pro->prd_id);
    @endphp 
    <tr class="closest-tr">
        <td>{{ ++$menuCounter }}</td>
        <td>{{ $member_info->usr_name }}</td>
        <td>{{ $product_info->prd_name }}</td>
    </tr>
@endforeach

But I wanted to know that, how can I retrieve usr_name & prd_name by User and Product Models relationships? Therefore, I won't need to add the Model names in the view and get data there...

I tried these two at the Controller, but these are both wrong:

Product::whereHas('favouritees')->get(); // if two different users add same product, it returns only one of them

User::whereHas('favourites')->get(); // if a user add different products, it returns only one of them for the user

So the question is, how can I show all the results from favourite_products at a table with User or Product Many To Many relationship?


Solution

  • To get all the data (product and users that favorite that product) get all the product with the users related to them

    $products = Product::whereHas('favouritees')->with('favouritees')->get(); 
    // if two different users add same product, it returns only one of them but it will have two users in the relation favouritees
    

    Then in you blade you can loop them

    @foreach($products as $product)
        @foreach($product->favouritees as $user)    
            <tr class="closest-tr">
                <td>{{ ++$menuCounter }}</td>
                <td>{{ $user->usr_name }}</td>
                <td>{{ $product->prd_name }}</td>
            </tr>
        @endforeach
    @endforeach