I am using laravel 5.1 for my project.
My issue was to dispaly the data as per category_id which foreign key of table category.
This code only get DATA having category_id 1 and this loop only run at $i=1 and after that they can not be iterate.
Please help me to solve out this issue.
My controller code was:-
public function category()
{
$category2=Category::all();
for($i=1;$i<=count($category2);$i++)
{
$category=HelpCenter::where('category_id','=',$i)->get();
return view('folder/category',compact('category'));
}
}
My view code was:-
#foreach($category as $category)
<li> {{$category->questions}}</li>
#endforeach
You cannot use the same variable for iterating as the array you are iterating ($category as $category). You MUST be getting some kind of error because of that.
That being said, you cannot return multiple views with a controller. You will just return the first result that you get.
What you should be doing is something like this:
public function category()
{
$category2=Category::all();
$categories = [];
for($i=1;$i<=count($category2);$i++)
{
$categories[]=HelpCenter::where('category_id','=',$i)->get();
}
return view('folder/category',compact('categories'));
}
And then in your view:
#foreach($categories as $category)
<li> {{$category->questions}}</li>
#endforeach
You are returning from the loop when it runs for one category. Just place your return line after closing loop braces. Like this..
public function category()
{
$category2=Category::all();
for($i=1;$i<=count($category2);$i++)
{
$category[]=HelpCenter::where('category_id','=',$i)->get();
}
return view('folder/category',compact('category'));
}
Hope this will solve your problem.
It is good to use relationship between Category and HelpCenter . For more info Check Here
But if you want to do this way then I think this is better way :
public function category()
{
$category2=Category::all();
$category = [];
foreach($category2 as $cat ){
$category[] = HelpCenter::where('category_id','=',$cat->id)->get();
}
return view('folder/category',compact('category'));
}
Related
Comparing to tables in Laravel. I have this code in my class (model):
public function table1() {
return $this->hasOne(table1Class::class, 'type', 'bms_id');
}
public function table2() {
return $this->belongsTo(table2Class::class, 'bms_id', 'type');
}
The controller, has something like this:
$type =
DB::table('table2')
->join('table1', 'table1.col_id','table1.col_name')
->select('table2.*', 'table1.*')
->get();
$dataMerge = $dataMerge->merge($type);
In the view, I have:
#foreach($data as $item)
{{$item->type==120}} //this works, no problem
{{$item->col_name}} //this produces nothing!
#endforeach
As you can see, the code stops working when referencing the col_name, any suggestions?
Thanks in advance!
I am trying to retrieve the data on my wishlist table, for a particular user, so far it only retrieves the first data on the table, just returning one array instead of the three in the table with same user id
public function getWishlistByUserId($id){
$wishlists = Wishlist::where('userId', $id)->get();
foreach($wishlists as $wishlist){
$products = Product::where('id', $wishlist->productId)->get();
return $products;
}
}
It happens because the foreach loop returns a value during the first iteration. Place your return statement outside the loop. Also you could improve your performence by making use of relationships.
An example could be:
// Product.php
public function wishlists()
{
return $this->hasMany(Wishlist::class);
}
// Your method
public function getWishlistByUserId($id)
{
return Product::whereHas('wishlists', function ($query) use ($id) {
$query->where('userId', $id);
});
}
Ideally this is n+1 situation
So i will suggest to use laravel relationship like:
in your whishlist model
public function product(){
return $this->hasMany(Product::class,'productId','id');
}
get data with relationship
public function getWishlistByUserId($id){
$wishlists = Wishlist::with('product')->where('userId', $id)->get();
}
I was finally able to get it working this way, i just pushed the result into an array, and then returned it outside the loop, thanks everyone for your help
public function getWishlistByUserId($id){
$wishlists = Wishlist::where('userId', $id)->get();
$wishlist = [];
foreach($wishlists as $wish){
$product = Product::where('id', $wish->productId)->get();
array_push($wishlist, $product);
}
return $wishlist;
}
In my routes/web.php I have a route like this...
Route::get('/tags/{tag}', 'TagsController#show');
Then, inside TagsController because I have a post_tag pivot table that has been defined as a many-to-many relationship.
Tag.php...
public function posts(){
return $this->belongsToMany(Post::class);
}
public function getRouteKeyName(){
return 'name';
}
Post.php...
public function tags(){
return $this->belongsToMany(Tag::class);
}
I get the posts for a certain tag like this...
public function show(Tag $tag){
$posts = $tag->posts;
return view('posts.index', compact('posts','tag'));
}
Then, to sort the posts into newest first I can do this in index.blade.php...
#foreach ($posts->sortByDesc('created_at') as $post)
#include('posts.post')
#endforeach
This works fine, but I'm doing the re-ordering at collection level when I'd prefer to do it at query level.
From Eloquent: Relationships I can see that I can do something like this, which also works...
$user = App\User::find(1);
foreach ($user->roles as $role) {
//
}
But, something like this does not seem to work...
public function show($tag){
$posts = \App\Tag::find($tag);
return view('posts.index', compact('posts'));
}
My question is, how can I filter/order the data at a query level when using pivot tables?
To order your collection you must change
public function tags(){
return $this->belongsToMany(Tag::class);
}
to
public function tags(){
return $this->belongsToMany(Tag::class)->orderBy('created_at');
}
Extending #leli. 1337 answer
To order content without changing the relation created.
First, keep the original relation
class User
{
public function tags
{
return $this->belongsToMany(Tag::class);
}
}
Second, during query building do the following
//say you are doing query building
$users = User::with([
'tags' => function($query) {
$query->orderBy('tags.created_at','desc');
}
])->get();
With this, you can order the content of tags data and in query level also if needed you can add more where clauses to the tags table query builder.
I have trouble with showing related variable in laravel blade
public function GetAll()
{
$news=DB::table('news')->get();
return View('index',['news'=>$news]);
}
In View:
#foreach($news as $new)
...
{{$new->comments()->count()}} Comments
...
#endforeach
Its also doesnt work for any variables of object but working good for first item:
public function Count()
{
$news=News::find(1);
echo $news->comments()->count();
}
public function GetAll()
{
$news = News::with('comments')->get();
return View('index',['news'=>$news]);
}
Use ORM instead of DB.
In my Menu controller I have a method which should display the specified record and all its children.
I have two models: MenuItem and MenuVariation, My items will have many variations as outlined in my methods:
MenuItem model
public function variant()
{
return $this->hasMany('App\MenuVariation');
}
MenuVariation model
public function item()
{
return $this->belongsTo('App\MenuItem', 'menu_item_id');
}
Now in my controller I have the following method:
public function show($id)
{
$item = MenuItem::findOrFail($id);
return $item;
}
...which currently only shows the item record but not its variations, so I have changed the code like this...
public function show($id)
{
$item = MenuItem::findOrFail($id)->with('variant')->get();
return $item;
}
but this oddly return ALL items and their variations.
Could someone help me get this working as desired? I would like to still utilise FindOrFail on the Item record, but it should also retrieve any variants (if found).
findOrFail will initiate the query, so you want to switch the order and put with in-front of it. Then use findOrFail. See Below:
public function show($id)
{
$item = MenuItem::with('variant')->findOrFail($id);
return $item;
}
There is also no need for get when you do that.