Laravel Mega Menu Loop - laravel

I am learning laravel and was trying to create a Megamenu. But I can call parent menu, I stacked at 1st child and 2nd child.
Same children coming under every parent.
<div class="navbar-mega">
<div class="dropdown-mega">
#php
$categories = App\Models\Category::where('parent_id', 0)->orderBy('order_level','ASC')->get();
#endphp
#foreach ($categories as $item)
<button class="dropbtn-mega"> {{$item->id}}</button>
#endforeach
<div class="dropdown-content-mega">
<div class="row-mega">
#php
$subcategories = App\Models\Category::where('parent_id',
$item->id)->orderBy('name','ASC')->get();
#endphp
#foreach ($subcategories as $subcategory)
<div class="column-mega">
<h3>{{$subcategories}}</h3>
</div>
#endforeach
</div>
</div>
</div>
</div>
Database Fields
Subcategory Query Output

This code :
$subcategories = App\Models\Category::where('parent_id',$item->id)->orderBy('name','ASC')->get();
is not within the loop through the $categories as $item. So when it is executed it will also return the same set of categories (as $item will always be the same value at that point in your code.
Put it within the loop :
#foreach ($categories as $item)
<button class="dropbtn-mega"> {{$item->id}}</button>
<div class="dropdown-content-mega">
<div class="row-mega">
#php
$subcategories = App\Models\Category::where('parent_id',
$item->id)->orderBy('name','ASC')->get();
#endphp
#foreach ($subcategories as $subcategory)
<div class="column-mega">
<h3>{{$subcategories}}</h3>
</div>
#endforeach
</div>
</div>
#endforeach
and it should work fine.

You can use append for fetch sub categories, in your category model use this,
protected $appends = [
'sub_categories'
];
public function getSubCategoriesAttribute()
{
return Category::where('parent_id', $this->id)->orderBy('name','ASC')->get();
}
<div class="navbar-mega">
<div class="dropdown-mega">
#php
$categories = App\Models\Category::where('parent_id', 0)->orderBy('order_level','ASC')->get();
#endphp
#foreach ($categories as $category)
<button class="dropbtn-mega"> {{ $category->id }}</button>
#endforeach
<div class="dropdown-content-mega">
<div class="row-mega">
#foreach ($category->sub_categories as $subCategory)
<div class="column-mega">
<h3>{{ $subCategory->name }}</h3>
</div>
#endforeach
</div>
</div>
</div>
</div>

The better way to use below code in controller. And create the relations in model.
$categories = App\Models\Category::where('parent_id', 0)->orderBy('order_level','ASC')->get();
Use child parent relation in your model:
public function children()
{
return $this->hasMany(Category:Class,'parent_id');
}
And use with to get as parent-child tree
$categories = App\Models\Category::with('children)->where('parent_id', 0)->orderBy('order_level','ASC')->get();
You can check it using
dd($categories);
and use loop on it easily.

I think your table structure is not appropriate. Maybe you are trying to create an infinity category, subcategory, and other staff. In that case, you may go through this.
Table columns name should be like
id parent_id level name .....
Brief :
id as primary key, parent_id will be foreign key of your db table primary id, and other columns will be as your expectation.
How to read all the staff?
You may follow the below steps.
$categories = Category::query()->where('parent_id',0)->get() // You may put order by something.
Note: What you will get from this query?
The answer is, you will get all the parent's categories.
Now read every single parents category and their childrens.
How to read parents' category and their children?
At First Read Parent category
foreach($categories as $key=>$category){
echo $category->name; // Your Parent Category is here.
}
Secondly, Read the Parent-Child category
foreach($categories as $key=>$category){
echo $category->name; // Your Parent Category is here.
// Must check is child category found or not. Otherwise your error can be arrise.
if($categories->subCategories->count()){
foreach($categories->subCategories as $k=>$subCategory){
echo $subCategory->name;
}
}
}
A question can be here $categories->subCategories->count() && foreach($categories->subCategories as $k=>$subCategory) ?
If you have a question like this.
The answer is below :
Note: You must add a relationship method inside Category Model like A Parent Category can be More Child SubCategory
add this method to your Category Model.
public function subCategories(){
return $this->hasMany(Category::class,'parent_id');
}
Now you will get smooth output.
Have fun.

Related

Undefined index: id Laravel 5.8

My Tables:
kategoris table
id | kode_kategori | kategori_name |
items table
id | kategori_id | item_name
In items table the kategori_id column has foreignkey.
My Controller:
public function edit($id)
{
// $item = Item::findOrFail($id);
$item = DB::table('items')
->join('kategoris', 'items.kategori_id', '=', 'kategoris.id')
->where('items.id', '=', $id)
->select('items.*', 'kategoris.*', 'items.id', 'items.kategori_id')
->get();
// dd($item);
return view('master-dev/item/edit', compact('item'));
}
My View:
<div class="card card-default">
{{ Form::model($item,['route'=>['item.update',$item['id']], 'files'=>true,'method'=>'PUT']) }}
<div class="card-header">
<h3 class="card-title"><b>Edit Data Item</b></h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body">
#if(!empty($errors->all()))
<div class="alert alert-danger">
{{ Html::ul($errors->all())}}
</div>
#endif
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ Form::label('kode_kategori', 'Kode Kategori') }}
<select name="kode_kategori" id="kode_kategori" class="form-control">
#foreach ($item as $i)
<option valu="{{ $i['kode_kategori'] }}">{{ $i['kode_kategori'] }}</option>
#endforeach
</select>
</div>
</div>
..........
..........
{{ Form::close() }}
I've tried any solutions in stackoverflow such as adding (ifempty...) and other solution but still the result Undefined index: id in my edit blade. When I was trying using dd and vardump the results was shown. I need to loop the foreach in my dropdown menu to show the list of data from my categories table. And I need to join my items table and my categories table to get the name of the categories.
you are calling same id from items and kategoris try this
public function edit($id)
{
// $item = Item::findOrFail($id);
$item = DB::table('items')
->join('kategoris', 'items.kategori_id', '=', 'kategoris.id')
->where('items.id', '=', $id)
->select('items.*', 'kategoris.id as kategory_id', 'kategoris.kode_kategori', 'kategoris.kategori_name')
->get();
// dd($item);
return view('master-dev/item/edit', compact('item'));
}
if this answer doesnot work show your database relation i will give you solution
$item = ....->get() will return a Collection to only have one item you need to use $item = ....->first() instead
But since you have #foreach ($item as $i) I believe, you still want to have a collection, but in that case, your issue is here
{{ Form::model($item,['route'=>['item.update',$item['id']], 'files'=>true,'method'=>'PUT']) }}
Since you have a collection, we don't know what $item['id'] it's referring to. Perhaps $item->first()['id'] ?
I solved the problem, there's a conflict fetching data from items and kategoris tables. There are differences calling a value with array and object, mostly if its data looped. So in the controller I must declared one by one, the selected value id from kategoris table, and I have to join both tables to get the name of the kategoris, and then I have to declare once more to get the list of the kategoris data. So there are three (3) variables to declare each one of them. For this long time I was looking for the short code in my Controller but I cannot find it.
Thank you for all of you guys helping me this problem. Cheers.

How can I filter the data of foreach?

I have this design:
I need to say: last post that I add it put it in the head of design then other put them down.
My shut :) Html and foreach code:
#if ($user->projects->count() > 0)
<section class="latest section shadow-sm">
<h1>Projects</h1>
<div class="section-inner">
#foreach ($user->projects->sortByDesc('id')->take(1) as $project)
<div class="item featured text-center ">
// head post
</div>
#endforeach
#foreach ($projects_last->sortByDesc('id') as $project)
<div class="item row">
// other post
</div>
#endforeach
</div><!--//section-inner-->
</section><!--//section-->
#endif
Code of controller for $projects_last:
$projects_last = $user->projects;
$projects_last->pop();
return view('frontend.user_profile',compact('user','projects_last'));
I have the problem with when I say if the #if ($user->projects->count() > 0) do not show any thing but still show me the <h1>Projects</h1> even it is empty!
And if you have any suggest to making my code better pls do it with thankful :)
To iterate Collections you have to get them. So you have to use get() to get the results.
...
#foreach ($user->projects->sortByDesc('id')->take(1)->get() as $project)
...
and
...
#foreach ($projects_last->sortByDesc('id')->get() as $project)
...
You can see here the documentation: Laravel query documentation
Note: if you want to get just one element in your first foreach loop you can use first() instead of take(1). You code will be like that:
#php($first_project = $user->projects->sortByDesc('id')->first())
#if (!is_null($first_project))
// Use $first_project as $project variable
#enif

How can I get images under a blog for a user

What I actually want is, for a specific user, I'm trying to show every image under a single blog. What I'm getting is a single blog post images for every blog.
Controller
$user_id = Session::get('id');
$user = Users::find($user_id);
$blogs = Blog::where('user_id', $user_id)->paginate(10);
$blogImage = BlogImage::where('blog_id', $blogs->pluck('id'))->get();
return view('Users.userlayout', compact('user', 'blogCat', 'blogs', 'username', 'blogImage'));
View Page
#foreach($blogs as $blog)
<div class="post">
#foreach($blogImage as $img)
<img src="{{asset('storage/blog_img/'.$img->blog_img)}}" alt="Image"
class="img-responsive">
#endforeach
<p>
<?php $str = $blog->blog_desc; ?>
{{str_limit($str, 250, "...")}}
</p>
<a href="{{URL::to('/blog-details/'.$blog->id)}}" target="_blank" class="btn_1">
Read more
</a>
</div>
<hr>
#endforeach
This is because you're using where instead of whereIn.
If you try and pass an array or a collection to where it will only use the first value.
$blogImage = BlogImage::whereIn('blog_id', $blogs->pluck('id'))->get();
Since this will return all of the BlogImage's associated with the Blog's the in the paginated list I would imagine you'll need to do a check to make sure you're only displaying the images that are associated with the specific Blog. One way you can do this is by using `#continue():
#foreach($blogImage as $img)
#continue($blogImage->blog_id !== $blog->id)
<img src="{{asset('storage/blog_img/'.$img->blog_img)}}" alt="Image" class="img-responsive">
#endforeach
All of that being said I would recommend using a one-to-many relationship between Blog and BlogImage:
Blog
public function images()
{
return $this->hasMany(BlogImage::class);
}
BlogImage
public function blog()
{
return $this->belongTo(Blog::class);
}
Then in your controller you can Eager load the images and have something like:
$blogs = Blog::with('images')->where('user_id', $user_id)->paginate(10);
And your blade file would have:
#foreach($blog->images as $image)
<img src="{{asset('storage/blog_img/'.$image->blog_img)}}" alt="Image" class="img-responsive">
#endforeach
You could then apply the same one-to-many relationship logic between User and Blog as well.

Pass two variable in one array and show it on view page in Laravel

I am trying to merge two arrays into a single one and return it (the merged array) into a view in order to format and display it.
Below is the method in my controller intended for that purpose;
public function showJobCategoryContent($id)
{
$jobsInfo = Job::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
$userInfo = Employee::all();
$array = array_merge($jobsInfo->toArray(), $userInfo->toArray());
return view('front.category-content.job-category-content', [
'jobsInfosById'=> $array
]);
}
Here, the content of my view;
#forelse($jobsInfosById as $jobInfoById)
<li>
<div class="well">
<h4>{{ $jobInfoById['company_name'] }}</h4>
<h4>{{ $jobInfoById['full_name'] }}</h4>
</div>
</li>
#endforelse
I get the following error:
Undefined index: company_name
What am I doing wrong and how can I resolve it?
use
$jobInfoById->company_name
instead of
$jobInfoById['company_name']

How can I solve issue with One to One relationship using foreign keys

I've been using eloquent in my models. I've got the following two tables:
Singlecard
->id
->card_id
Card
->id
->card_id
My Singlecard Model has the following function:
public function info()
{
return $this->hasOne('Card', 'card_id', 'card_id');
}
I used this to get the card (there's only one card in the deck for my test).
$cards = Singlecard::where('deck_id', '=', $deck)->get();
foreach ($cards as $card)
{
$cards_array[] = $card;
}
It got the correct card and using var_dump I verified that. However, here's the problem:
<div class="row singlecard">
<a class="" href="{{ $single->id }}">
<div class="large-2 columns">
<img src="{{ $single->info->card_image }}">
</div>
<div class="large-10 columns">
<div class="row">
<div class="large-12 columns">
<p>{{ $single->info->name }}</p>
</div>
</div>
<div class="row">
<div class="large-12 columns">
#foreach ($single->attributes as $attribute)
<p>{{ $attribute->alias }}</p>
#endforeach
</div>
</div>
</div>
</a>
</div>
Here's the twist: The attributes code works correct. It grabbed the correct attributes from a one to many relationship I defined. But it's grabbing the wrong info from the Cards table. Even though I defined the keys to match on, it is matching based on the ID of the singlecard and the card_id in the Cards table.
I've tried removing the keys and that didn't do anything. I even removed the function all together just to verify that that was the function being called. I'm not sure what's wrong?
UPDATE:
I figured it out, I did two things. One, I used id from the Cards table as the record to match with Singlecards. I also changed my function in the Singlecards model like so:
public function info()
{
return $this->belongsTo('Card', 'card_id');
}
This allowed me to properly query the relationship.
I needed to update how my models were related and better form the relationship. I also needed to change the model so that Singlecards belonged to Cards. I assumed it should be the opposite.
Cards contains all the info about the various cards and Singlecards is what is in each individuals hands/decks. I assumed that would make Singlecards the parent but that was a mistake. Once I changed the function in the model to be like this:
public function info()
{
return $this->belongsTo('Card', 'card_id');
}
Then it worked.

Resources