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

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.

0

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

https://prnt.sc/b_D_9l_Ldvn-

0

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)
    @php
        $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;
        }
    @endphp

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

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

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Akash akash-sharma Joined 28 Dec 2022

Moderators

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

Your logo here?

Laravel.io

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

© 2024 Laravel.io - All rights reserved.