Laravel send data from one model to another inside a foreach - php

I need to send the data (price) in my example to the view but inside foreach.
In my project, I have product data (title, img, etc.) in one table from Database.
But each product has a lot of variants and I put the variants to another table.
In the view, I have foreach which loops me 12 products.
I need to put the price inside each product.
The problem is to define each product's id in my controller.
products.blade.php:
#foreach($products as $product)
<div> {{ here I need to put the price }} </div>
<div> {{ $product->slug }} </div>
#endforeach
ProductsController.php:
// all prices for my variants
$variants_prices = Variants
::where('product_slug', '=', $slug)
->get('attribute_price');
// minimum price
$min_price = $variants_prices
->where('attribute_price', $variants_prices->min('attribute_price'))
->first();
// take value of minimum price from all variants
$pdt_min_price = $min_price->attribute_price;
return view('products.index')
->with('pdt_min_price', $pdt_min_price);
I need to have something like this in my blade file:
I will be very glad if somebody will help me to solve this problem.

You can define a relationship in your model between Product and Variant
in your Product model:
function variant()
{
return $this->hasMany('App\Variant', 'foreign_key');
}
then you can get the variant using:
$products = Product::with(['variant'])->get();
then at the loop your can access the variant using its key:
{{ $product->variant[$key]['price'] }}

Related

create counter for blog categories in laravel

I´m traying to create one counter for my blog´s categories. This should appear to the right name side of my category . i´m using my model with variable appends, that after i will use in my blade for show my result in one span. But i don´t know very well how i can use count in my Model. I´m doing this in my model Blog.
my variable appends contain:
protected $appends = [
'custom_fields',
'has_media',
'restaurant',
'blog_category',
'viewer',
'postCounter',
];
i´m traying this:
return $this->blogs()->count();
i have a relation between blog and blog_category with:
public function blogCategory()
{
return $this->belongsTo(\App\Models\BlogCategory::class, 'blog_category_id', 'id');
}
i want to do in my view appear for example:
innovation (2)
in my view i´m doing this:
#foreach($categories as $category)
<li>{{ trans('web.blog_category_'.$category->name) }}<span>{{$category->postCounter}}</span></li>
#endforeach
but always returned me 0, and i have post with categories
updated
With laravel relationship withCount you can do this easily. If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.
add withCount method to your query
$categories = Category::withCount('blogCategory')->get();
You can access the count in your foreach loop
// $category->blogCategory_count
#foreach($categories as $category)
<li>
<a href="{{ url('blogs/'.$category->name) }}">
{{trans('web.blog_category_'.$category->name) }}
</a>
<span>{{$category->blogCategory_count}}</span>
</li>
#endforeach

Laravel filter products by category name

I use Bagisto E-Commerce platform (build laravel + vue) and I have created package where I want list categories and filter products by category name.
I don't know how exactly filter products by one view and in bagisto they list products by category page e.g. example.com/category-name
I try to use this example, but can't get it working, because I don't know where I get class "Products" and function AllProducts.
Can someone guide me in the right direction of how I could get this to work correctly?
This is what I'm trying to do: https://codepen.io/mrsingleton/pen/aYVBvV
My code in products view:
$categories = [];
foreach (app('Webkul\Category\Repositories\CategoryRepository')->getVisibleCategoryTree(core()->getCurrentChannel()->root_category_id) as $category) {
array_push($categories, $category);
}
?>
#if (count($categories))
<div class="list-container" style="text-align:center;margin-top: 50px;">
<ul class="list-group">
#foreach ($categories as $key => $category)
<li> {{ $category->name }} </li>
#endforeach
</ul>
</div>
#endif
In Bagisto, Laravel translatable has been used. Thats why you need to use the different approaach to achieve this. As directly by name, you won't be able to achive because the rest columns are on different tables i.e. category_translations.
If you check the Categories model in namespace i.e. Webkul\Category\Models\Category, it is already linked to the Product model. So you can directly chain it to fetch all associated products.
/* fetch category by name */
$categoryName = 'Category 1';
$category = Category::whereHas(
'translations',
function ($query) use ($categoryName) {
$query->where('name', $categoryName);
}
)->first();
$relatedProducts = $category->products;
/* rest is your operations */

Colour ID is being fetched from productcolours table but how to get colour name from colours table

$product = Products::where('product_slug', $slug)->first();
$productcolours = Productcolour::all()->where('product_id', $product->id);
$colour = Colour::all();
product.blade
#foreach($productcolours as $productcolour)
{{$productcolour->color_id}}
#endforeach
Fetch colour name
You should be able to set up a belongsToMany relationship between Products and Colour e.g. add the following to your Products model (if it doesn't already exists):
public function colors()
{
return $this->belongsToMany(Color::class);
}
Without seeing your table definitions I wouldn't be able to say for certain that the above code will work as is. It is currently assuming that you've followed Laravel's standard naming convention.
Then you should simply be able to load the relationship:
$product = Products::with('colors')->where('product_slug', $slug)->first();
#foreach($product->colors as $color)
{{ $color->name }}
#endforeach
Just an FYI, in the future I would recommend filtering using the database rather than retrieving all of the records and then filtering them down i.e.
this:
$productcolours = Productcolour::all()->where('product_id', $product->id);
would become:
$productcolours = Productcolour::where('product_id', $product->id)->get();
Add below code into your product model
public function color()
{
return $this->hasOne('App\Productcolour', 'id', 'color_id');
}
Above code will work when your product table color_id match with color table id
to show in front end use below code(1 is a product id, use your dynamic id $product->id)
{{Products::find(1)->color}}
or
in controller $colour = Products::find(1)->color;

Puling a specific item from a foreach loop in Laravel

I have a project with 2 tables(Categories and products). They have One to Many relationship. Many products have one Category. Am pulling products of a specific category(together with its price and description) and storing in one variable so that I can use in the view. In the view am having a foreach loop whereby I want to display each row from the products table of a specific category(a product with its price and description) but it fails,,please assist?
FrontController
public function itemOne() {
//Get all phones(Have category of 1 ) in categories table
$mobile = Category::find(1)
->products()
->whereNotNull("image")
->whereNotNull("name")
->whereNotNull("description")
->whereNotNull("price")
->whereNotNull("category_id")->get();
return view('front.products')->withItems($mobile);
}
Products.blade.php
#foreach($items as $item)
<img src="{{ asset('images/'.$item->image) }}">
<br> {{ $item->name}} <br> {{ $item->price }}
#endforeach
public function itemOne() {
//Get all phones(Have category of 1 ) in categories table
$mobile = Category::find(1)
->products()
->whereNotNull("image")
->whereNotNull("name")
->whereNotNull("description")
->whereNotNull("price")
->whereNotNull("category_id")->get();
return view('front.products',compact('items'));
}
use compact in return

Select from two tables and show everything in laravel

I want to show on the page data from two tables but with a little condition and I can't figured it out how to make it in Laravel 4.
So I have table categories and table products. Currently I show all categories on the page and there is no problem. The problem is now there will have products without category and I want to loop them also on the page.
When admin create product he choose category but if doesn't choose any it will save 1 default in database products column single_product.
This is Product model
public function categories()
{
return $this->hasMany('Categories', 'category_id');
}
And Categories model
public function products()
{
return $this->hasMany('Product', 'category_id');
}
public function lowestProduct() {
return $this->products()->selectRaw('*, max(price) as aggregate')
->groupBy('products.product_id')->orderBy('aggregate');
}
And this is the view
<div class="col-xs-8 text-left" style="margin-top: 9px">
#if($category['no_category'] == 0)
Price: <strong>{{ $category->products()->min('price') }} $</strong>
#else
Price from: <strong>{{ $category->products()->min('price') }} $</strong>
#endif
</div>
How to select single column from products table and show them on the page along with categories name?
Then there is no category. Avoid your category class and just fetch directly from the product class. Create a function like:
public function singleItems()
{
return $this->where("single_product", 1)->get();
}
Then you foreach the result out. Please check this for further information:
https://laravel.com/docs/5.1/eloquent-collections
I know above is for another version of laravel than yours, but I think it should work. Else tell me, then I will look further.

Categories