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)
@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
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community