Support the ongoing development of →
Eloquent Laravel Authorization
Last updated by @tvbeek 1 year ago.

Hello @akash-sharma

Can you give more information about your database structure? That can help in giving the answer.

ps. I have updated your post to set the return in a code block.


Hi tvbeek, Thanks !! Here is my database structure kindly have a look. I need something from eloquent, query builder and loops make process slow.


To achieve the desired functionality, you can use Laravel's Eloquent relationships and conditional statements to load the prices from the appropriate table. Here's how you can do it:

Define the relationships in your Product and User models. Assuming you have a GroupPrice model and the related table has columns like group_id, product_id, price_GBP, price_euro, and price_usd:

// In Product model
public function groupPrices()
    return $this->hasMany(GroupPrice::class);

// In User model
public function group()
    return $this->belongsTo(Group::class);

In your controller, use the with() method to load the group prices conditionally based on the user's group:

$products = Product::query();

if (Auth::check()) {
    $userGroupId = Auth::user()->group_id;
    $products->with(['groupPrices' => function ($query) use ($userGroupId) {
        $query->where('group_id', $userGroupId);

$products = $products->paginate(6);

In your view, you can now use the group prices if they exist or fall back to the default prices from the product table:

@foreach ($products as $product)
        $priceGBP = $product->price_GBP;
        $priceEuro = $product->price_euro;
        $priceUSD = $product->price_usd;

        if ($product->groupPrices->isNotEmpty()) {
            $groupPrice = $product->groupPrices->first();
            $priceGBP = $groupPrice->price_GBP;
            $priceEuro = $groupPrice->price_euro;
            $priceUSD = $groupPrice->price_usd;

    {{-- Display the prices --}}
    <p>GBP: {{ $priceGBP }}</p>
    <p>Euro: {{ $priceEuro }}</p>
    <p>USD: {{ $priceUSD }}</p>

This approach allows you to conditionally load the group prices for the authenticated user and display them in the view. If the user is not logged in or has no group prices, the default prices from the product table will be used


Sign in to participate in this thread!


Your banner here too?

Akash akash-sharma Joined 28 Dec 2022


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 - All rights reserved.