how to display video per category in laravel eloquent - php

model video
protected $table = 'lokit_video';
protected $fillable =
[
'title',
'cover_img',
'trailer',
'url',
'order_',
'active',
'description',
'lokit_category_id',
'duration'
];
public function lokit_category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
model category
protected $table = 'lokit_category';
protected $fillable = ['name'];
in controller
public function index(){
$dataCategory = Category::all();
$dataVideo = Video::all();
$video = Video::where('lokit_category_id', $dataCategory)->get();
dd($video);
return View('bnpt.content.home',compact('dataCategory','dataVideo'));
}
when I try the code above what happens with the code is null, how to fix it?

If you want to get all the videos related to all the categories, you should develop the relationship.
In Category Model:
public function videos()
{
return $this->hasMany(Video::class);
}
In the controller method:
$dataCategory = Category::all();
return View('bnpt.content.home',compact('dataCategory'));
In the view file:
<ul>
#foreach($dataCategory as $category)
<li><span>{{$category->name}}</span>
<ul>
#foreach($category->videos as $video)
<li><span>{{$video->name}}</span></li>
#endforeach
</ul>
</li>
#endforeach
</ul>

[PROBLEM]In your code you have
$dataCategory = Category::all();
$video = Video::where('lokit_category_id', $dataCategory)->get();
$dataCategory is a collection of the model instances of all the entries in your lokit_category table.
[SOLUTION]
You can't compare a collection with a field that expects an id in your case in the where statement.
lokit_category_id should be compared with the id of a category.
If you have the lokit_category_id
$videos = Video::where('lokit_category_id', $lokit_category_id)->get();
dd($videos);
If you have the name of the lokit_category, get the id using that name and then make the query.
// Get the category for which you want to get all the videos.
$categoryName = 'CATGEORY NAME';
$category = Category::where('name', $categoryName)->first();
$videos = Video::where('lokit_category_id', $category->id)->get();
dd($videos);
[IF YOU WANT VIDEOS WITH RESPECT TO A CATEGORY]
In your Category Model
public function videos(){
return $this->hasMany(App\Video::class, 'lokit_catgeory_id', 'id');
}
Controller
Use eager loading as it will help in reducing the number of queries.
$categories = Category::with('videos')->get();
foreach($categories as $category){
// You can access the videos for the category using the videos relation.
$category->videos;
}

Related

Single category and multi categories

I have articles witch can have one single category that's Main category with category_id.
and additional multi categories with pivot table everything working it's stores but i can't get data on web i'm only getting articles with single category how can i get articles with single and with multi categories in one variable?
article model:
public function category()
{
return $this->belongsTo(AllCategory::class, 'category_id', 'id');
}
public function manyCategories()
{
return $this->belongsToMany(AllCategory::class, 'articles_categories', 'article_id', 'category_id')
->using(ArticleCategory::class);
}
AllCategory model:
public function articles()
{
return $this->hasMany(Article::class, 'category_id', 'id')->orderBy('published_at', 'Desc');
}
public function manyArticles()
{
return $this->belongsToMany(Article::class, 'articles_categories', 'category_id', 'article_id')
->using(ArticleCategory::class);
}
and pivot table:
class ArticleCategory extends Pivot
{
use HasFactory;
public $table = 'articles_categories';
protected $fillable = [
'article_id', 'category_id'
];
protected $guarded = ['*'];
}
and in controller i'm getting like this
$offsetPage = ($page - 1);
$perPage = 24;
$category = AllCategory::bySlug($slug);
if (! $category) {
abort(404);
}
$categoryArticles = $category->articles()
->with('manyCategories')
->skip($perPage * $offsetPage)
->take($perPage)
->get();
I'm getting single category articles with articles() and i'm trying to get manycategories to ->with but it's only getting me single category articles what i'm doing wrong?
You could create an accessor that would add the main category to the Collection of categories that the Article belongs to.
public function getCategoriesAttribute()
{
// adding the main category (if there is one) to the Collection
return (clone $this->manyCategories)->when(
this->category,
fn ($collection, $category) => $collection->prepend($category)
);
}
Controller:
$categoryArticles = $category->articles()
->with(['category', 'manyCategories'])
->skip($perPage * $offsetPage)
->take($perPage)
->get();
View:
#foreach ($articles as $article)
#foreach ($article->categories as $category)
...
#endforeach
#endforeach
Laravel 8.x Docs - Eloquent - Mutators & Casting - Defining an Accessor
Laravel 8.x Docs - Collections - Available Methods - when
Laravel 8.x Docs - Collections - Available Methods - prepend

How to fetch 2 products from every category

I want to fetch 2 products from every category.
Product.php
class Product extends Model
{
protected $table = 'products';
}
Category.php
class Category extends Model {
protected $table = 'categories';
}
Controller
public function index() {
$products = Product::all();
return Product::latest()->take(5)->get();
}
This should fetch the first two products of each category:
// Get all categories
$categories = Category::all();
//Create an empty array to store our product IDs
$prodIds = array();
// Extract the first 2 product IDs in each category
foreach ($categories as $category) {
$prodIds[] = $category->products->take(2)->pluck('id');
}
// Fetch products from their IDs
$products = Product::findMany($prodIds);
Edit: Also my answer above should work, it will fail if the category doesn't have at least two products. To fix this, you would need to remove empty values from $prodIds.
Product.php
class Product extends Model
{
protected $table = 'products';
public function Category()
{
return $this->belongsTo(Product::class);
}
}
Note : import your category model in Category model
Category.php
class Category extends Model {
protected $table = 'categories';
public function Product()
{
return $this->hasMany(Product::class);
}
}
Note : import your category model in Product model
Controller
public function index() {
return Category::with('Product'=>funcation($obj){
return $obj->take(2);
})->latest()->take(5)->get();
}
try this
$products = Product::latest()->take(2)->with('categories')->get();

How to get the count and values of item in a subcategory with parent_id in Laravel

How do I get the count and values of all items within a subcategory that has a parent_id. I have a category model which is related to the product model. And in the category table, there are parent_ids and their subcategories. How do I return all the products belonging to a parent category?
The database is shown below
Database
The Relationships are shown here
public function products()
{
return $this->hasMany('App\Product');
}
public function category()
{
return $this->belongsTo('App\Category');
}
Then in my controller, this returns 0 as count
public function niche($url)
{
$niche = Category::where('url',$url)->first();
$categories = Category::where('parent_id',$niche->id)->get();
$products = [];
foreach($categories as $category) {
$products = Product::where('category_id',$category->id)->get();
}
dd($products->count());
}
Output
Please how do I get the number of products belonging to this niche?
Thanks.
I think products() is a relationship method of products and categories
Can you try like this:
$products = [];
foreach($categories as $category){
array_push($products, $category->products());
}
dd(count($products, true));
I think this is happening because every time you go through a loop you create a new product variable, thus it will always dump out the count of the last category in the loop.
You should try something like this:
public function niche($url){
$niche = Category::where('url',$url)->first();
$categories = Category::where('parent_id',$niche->id)->get();
$products = [];
foreach($categories as $category){
array_push($products,$category->products());
}
dd($products->count());
}
I think the result is 0 maybe because the last sub category doesn't have any product.
Btw, I suggest a bit cleaner approach in this base. Lets define a sub categories relationship for a category.
class Category extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
public function subCategories()
{
return $this->hasMany(static::class, 'parent_id');
}
}
So you are able to access the products and the number of products in a number of ways:
// You can eager load for performance.
$category = Category::with('subCategories.products')->where('url', $url)->first();
$products = $category->subCategories->flatMap->products;
$count = $products->count();
// Or you can eager load JUST the number of products.
$category = Category::withCount('subCategories.products')->where('url', $url)->first();
$numberOfProducts = $category->products_count;
You have to use withCount on children relationship.
$categories = Category::whereNULL('parent_id')->with(['categories' => function ($query) {
$query->withCount('products');
}])->get();
Hopefully should be work

Displaying Products of a particular category in Laravel 5.4

I am building an e-commerce project using Laravel 5.4, I have got 2 tables which have the following columns:
categories: id, name , timestamps
Products: id , name, price, description, size , image , category_id , timestamps
The two tables are interlinked via one to many relationship(One Category has many products). I am uploading images and storing inside public/images folder in my Laravel app while the image name is stored in the database. When I upload everything is working fine, but when I pull images of a particular category so as to display in a view called Front.blade.php which is controlled by frontcontroller, I get blank fields(it doesnt pull the images). Please assist?
Category model
class Category extends Model
{
protected $fillable = ['name'];
public function products(){
return $this->hasMany('App\Product');
}
}
Product Model
class Product extends Model
{
protected $fillable = ['name', 'desctiption' , 'size', 'category_id', 'image'];
public function category()
{
return $this->belongsTo(Category::class);
}
}
Products Controller
public function store(Request $request)
{
$formInput[]=$request->image;
//validation
$this->validate($request,[
'name'=>'required',
'size'=>'required',
'description' => 'required|min:12',
'price'=>'required',
'category_id' => 'required',
'image'=>'image|mimes:png,jpg,jpeg,gif|max:100'
]);
$image=$request->image;
if($image){
$imageName=$image->getClientOriginalName();
$image->move('images',$imageName);
$formInput['image']=$imageName;
}
//Instantiate a new Project called Product
$product = new Product;
//Add the products to the Object
$product->description = $request->description;
$product->name = $request->name;
$product->price = $request->price;.
$product->image = $imageName;
$product->category_id = $request->category_id;
$product->size = $request->size;
//Save all the items to the database
$product->save();
}
FrontController
public function index(){
$items = Category::find(6)->products()->where('image' , true)->get();
return view('front.index')->withItems($items);
}
Front.blade.php
#foreach($items as $item)
<img src="{{ asset('images/'.$item->image) }}">
#endforeach
Replace where() clause with orwhere() as below to only return where images == true
public function index(){
$items = Category::find(6)->products()->orWhere('image','<>','')->get();
return view('front.index', compact('items'));
}

Laravel : How to access many to many relationship data Ask

I have category and subcategory table with many to many relationship
class Category extends Model {
protected $table='categories';
protected $fillable=['name'];
public function subcategories() {
return $this->belongsToMany('App\Modules\Subcategory\Models\Subcategory', 'categories_subcategories', 'category_id', 'subcategory_id');
}
}
Subcategory
class Subcategory extends Model {
protected $table='subcategories';
protected $fillable=['name'];
public function categories()
{
return $this->belongsToMany('App\Modules\Category\Models\Category', 'categories_subcategories', 'subcategory_id', 'category_id');
}
}
in controller
public function catSubList()
{
$subcategories = Subcategory::with('categories')->get();
return view('Subcategory::category_subcategory',compact('subcategories'));
}
But in view when i tried to access the data with following view
#foreach($subcategories as $row)
<td>{{$i}}</td>
<td>{{$row->name}}</td>
<td>{{$row->categories->name}}</td>
#endforeach
I got the error like :
ErrorException in Collection.php line 1527: Property [name] does not exist on this collection instance.
How do i access $row->categories->name ? anyone with the suggestion please?
You have to make another foreach() loop Because your subcategories belongsToMany categories. row->categories returns a collection, not an object. Thus the error.
<td>{{$row->name}}</td>
<td>{{$row->categories->name}}</td>
#foreach($row->categories as $category)
<td>{{$category->name}}</td>
#endforeach
Update
Getting a category with all subcategories. Simply invert your query
$category = Category::with('subcategories')
->where('name', '=', 'cars')
->first();
//will return you the category 'cars' with all sub categories of 'cars'.
Without eager loading
$category = Category::find(1);
$subacategories = $category->subcategories;
return view('Subcategory::category_subcategory', compact('category', subcategories));

Categories