How to use two foreachs in laravel? - php

I have a category table, it is organized by 'parent_id' and 'categoryid'. I need to organize it in a list, where I group the parent class with the daughter class.
I created this code.
In the controller I get the value of the categories.
public function index()
{
$cat1 = Category::where('erp_parentid', '=', 0)->get();
foreach($cat1 as $categoria1){
$cat2 = Category::where('erp_parentid', '=', $categoria1->erp_categoryid)->get();
return view('admin.categories')->with('cat1', $cat1)->with('cat2', $cat2);
}
}
$cat2 is the child category, I get its values through the categoryid of the parent category.
But when I pass the values to the view, all parent categories take the same value as the first.
I used that code to display the values in the view:
<div class="container">
<div class="row">
<ul class="list-group">
#foreach($cat1 as $value)
<a data-toggle="collapse" data-target="#catfilha{{$value->erp_categoryid}}"><li class="list-group-item">{{$value->erp_name}}</li></a>
<ul id="catfilha{{$value->erp_categoryid}}" class="collapse">
#foreach($cat2 as $value2)
<li>{{$value2->erp_name}}</li>
#endforeach
</ul>
#endforeach
</ul>
</div>
</div>
I searched for similar cases here on the site, but found no resemblance, any suggestions? Thank you in advance.

You should define the relations in the model and call them in the view. Try something like this:
In Category Model:
public function getParent()
{
return self::where('erp_parentid', '=', $this->erp_categoryid)->get();
}
In Controller:
public function index()
{
$cat1 = Category::where('erp_parentid', '=', 0)->get();
return view('admin.categories')->with('cat1', $cat1);
}
In the View:
<div class="container">
<div class="row">
<ul class="list-group">
#foreach($cat1 as $value)
<a data-toggle="collapse" data-target="#catfilha{{$value->erp_categoryid}}"><li class="list-group-item">{{$value->erp_name}}</li></a>
<ul id="catfilha{{$value->erp_categoryid}}" class="collapse">
#foreach($value->getParent() as $value2)
<li>{{$value2->erp_name}}</li>
#endforeach
</ul>
#endforeach
</ul>
</div>
</div>
In your code, the return statement is inside the loop, so cat2 will be always the categories from the first item of cat1.

Related

Query AncestryOf with Laravel-nestedset in Laravel 5.8

I am using Laravel-nestedset and am having a hard time querying the ancestrosOf my category model.
This is what I am trying to do:
Works
http://carnival-experts.test/categories (this gives me a list of all categories)
http://carnival-experts.test/categories/carnival-games (this gives me a list of all Carnival Games)
Does Not Work
http://carnival-experts.test/categories/carnival-games/large-scale-games (this shows me a list of Carnival Games and not the Large Scale Games category)
I am sure this is just my lack of understanding--any help appreciated.
web.php
...
Route::get('/', 'CategoryController#index')->name('categories');
Route::get('/{category}/{slug?}', 'CategoryController#show')->name('show');
...
CategoryController.php
...
class CategoryController extends Controller
{
public function index()
{
$categories = Category::get()->toTree();
return view('categories.index', compact('categories'));
}
public function show(Category $category, $slug = null)
{
if (!is_null($slug)) {
$categories = Category::ancestorsOf($category);
return view('categories.show_subcategory', compact('categories', 'category', 'slug'));
} else {
return view('categories.show', compact('category'));
}
}
}
show_category.blade.php
...
#foreach($category['children']->chunk(3) as $chunk)
<div class="row">
#foreach($chunk as $category)
<div class="col-md-4" style="margin-bottom: 2rem">
<div class="feature-box center media-box fbox-bg">
<div class="fbox-media">
<a href="/categories/{{$category->slug}}">
<img class="image_fade"
src="https://*****.s3-us-west-1.amazonaws.com/{{ $category->photo }}"
alt="Featured Box Image"
style="opacity: 1;"></a>
</div>
<div class="fbox-desc">
<h3>{{$category->name}}</h3>
<span>Learn More</span>
</div>
</div>
</div>
Products
#if(count($category->products) > 0)
#foreach($category->products as $product)
{{$product->title}}
#endforeach
#endif
#endforeach
</div>
#endforeach
...

How to pass parameter to model function from view?

I have tree structure of categories. Now I have to display only that categories which is not applied in a particular business.
Code in Controller
public function edit($id)
{
try
{
$id=Crypt::decrypt($id);
$business=Business::findOrFail($id);
$business_contact_details=BusinessContactDetails::where('business_id',$id)->select('contact_no','id')->get();
$business_working_hours=BusinessWorkingHours::where('business_id',$id)->get();
$business_categories=BusinessCategories::leftJoin('categories','categories.id','=','category_id')->where('business_id',$id)->where('categories.parent_id','0')->select('categories.name as name','approved','category_id','business_categories.id as id')->get();
$categories = Categories::where('parent_id', '=', 0)->get();
return view('admin.businesses.edit',compact('business','business_contact_details','business_working_hours','categories','category_counter','business_categories'));
}
catch(DecryptException $e)
{
return view('errors.404');
}
}
Code in Model
public function subChilds(){
return $this->hasMany('App\Categories','parent_id','id')->whereNotExists(function($query){
$query->from('business_categories')->whereRaw('categories.id=business_categories.category_id')->where('business_id',2);
});
}
Code in edit View
<div class="col-md-6">
<ul id="tree1">
#foreach($categories as $category)
<li>
<input type="checkbox" value="{{$category->id}}" name="categories[]">
{{ $category->name }}
#if(count($category->subChilds($business->id)))
#include('admin.businesses.manageChildSub',['subChilds' => $category->subChilds($business->id)])
#endif
</li>
#endforeach
</ul>
</div>
Code in manageChildSub View
<ul>
#foreach($subChilds as $child)
<li>
<input type="checkbox" value="{{$child->id}}" name="categories[]">
{{ $child->name }}
#if(count($child->childs))
#include('manageChildSub',['subChilds' => $child->subChilds($business->id)])
#endif
</li>
#endforeach
</ul>
Here, You can see that I have passed business_id as 2, but I have to pass it as my current business ID. Basically I need to call the model function with ID.
After changing to this, I am not getting any subcategories.
You can try this:
public function subChilds($business_id){
return $this->hasMany('App\Categories','parent_id','id')
->whereNotExists(function($query) use ($business_id){
$query->from('business_categories')
->whereRaw('categories.id=business_categories.category_id')
->where('business_id', $business_id);
});
}

Display posts belonging to category in laravel

I am trying to get the posts that belong to each category, i had this working before but i can't seem to find what i have done wrong here.
I have a Post Table and a Categories Table
ROUTE
Route::get('articles/category/{id}', ['as' => 'post.category', 'uses' => 'ArticlesController#getPostCategory']);
CONTROLLER
public function getPostCategory($id)
{
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
$categories = PostCategory::all();
// return view
return view('categories.categoriesposts')->with('postCategories', $postCategories)->with('categories', $categories);
}
VIEW
#foreach($postCategories->posts as $post)
<div class="well">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placekitten.com/150/150">
</a>
<div class="media-body">
<h4 class="media-heading">{{ substr($post->title, 0, 50) }}</h4>
<p class="text-right">By Francisco</p>
<p>{{ substr($post->body, 0, 90) }}</p>
<ul class="list-inline list-unstyled">
</ul>
</div>
</div>
</div>
#endforeach
POST MODAL
public function postCategory()
{
return $this->belongsTo('App\PostCategory');
}
POSTCATEGORY MODAL
class PostCategory extends Model
{
// connect Categories to Posts tables
protected $table = 'post_categories';
// Category belongs to more than 1 post
public function posts()
{
return $this->hasMany('App\Post', 'post_category_id');
}
}
I can't see what i am doing wrong every time I go to a category it shows
Trying to get property of non-object
Any help will be much appreciated thanks
replace your lines:
$postCategories = PostCategory::with('posts')
->where('post_category_id', '=', $id)
->first();
with:
$postCategories = PostCategory::find($id)->posts;
Change your line in your PostCategoryModel to:
return $this->hasMany('App\Post', 'post_category_id','post_category_id');

Update multible rows in laravel 4

I wanted to update multiple rows in the database and have found a way to do it. but it does not seem like the best way to do it, since it is doing it in multiple calls at the moment.
I wanted to now if there is a better way to do this.
The homecontroller with the updatePersons function:
<?php
class HomeController extends BaseController {
public function index()
{
$persons = Person::get();
return View::make('hello')
->with(compact('persons'));
}
public function updatePersons()
{
$persons = Person::get();
foreach ($persons as $person) {
$person->fname = Input::get('fname'.$person->id);
$person->lname = Input::get('lname'.$person->id);
$person->save();
}
return Redirect::route('home')->with('succes', 'Siden er opdateret');
}
}
the view with the form
#extends('layouts.master')
#section('content')
<div class="container">
<ul class="list-group">
{{ Form::open(array('route'=>'personUpdate', 'method' => 'post')) }}
#foreach ($persons as $person)
<li class="list-group-item">
{{ Form::text('fname'.$person->id,$person->fname,array('class'=>'form-control', 'placeholder'=>'fname')) }}
{{ Form::text('lname'.$person->id,$person->lname,array('class'=>'form-control', 'placeholder'=>'lname')) }}
</li>
#endforeach
<li class="list-group-item">
<div class="box-footer">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</li>
{{ Form::close() }}
</ul>
</div>
</div>
#stop
The routes:
<?php
Route::get('/', array('as'=>'home', 'uses'=>'HomeController#index'));
Route::post('/', array('as'=>'personUpdate', 'uses'=>'HomeController#updatePersons'));
I have tried to use the savemany() function on $persons after the foreach loop in updatePersons() but with no results.
If you're updating many rows with each with different values, there's no easier way to do it.
Could you think of how you'd write this in SQL?

model function call in blade view laravel

My model code
how we can call this function in blade.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BasicModel extends Model
{
public static function get_product_count($id){
$query = "select COUNT(sub_id) AS count FROM products WHERE products.sub_id = $id";
print_r($query);
return $query->row_array();
}
}
My view.blade.php code
count in foreach loop or show in all category
#foreach ($r as $row)
<li class="grid-item type-rent">
<div class="property-block">
<img src="{{ URL::to('/template/images/background-images/sub-category-images/' .$row->sub_cat_images. '')}}" alt=""> <!-- <span class="images-count"><i class="fa fa-picture-o"></i> 2</span> <span class="badges">Rent</span> -->
<div class="property-info">
<h4>{{ ucwords(substr($row->sub_cat_name, 0, 22)) }}</h4>
<span class="location">NYC</span>
<div class="price"><strong>Items</strong><span>
<!-- start count code from here -->
$data = $this->BasicModel->count {{ ($row->sub_id) }}
echo $data['count'];
</span></div>
</div>
<!-- <div class="property-amenities clearfix"> <span class="area"><strong>5000</strong>Area</span> <span class="baths"><strong>3</strong>Baths</span> <span class="beds"><strong>3</strong>Beds</span> <span class="parking"><strong>1</strong>Parking</span> </div> -->
</div>
</li>
#endforeach
My BasicController Code
public function grid(Request $request, $id)
{
if ($id == 1) {
$r = DB::table('sub_category')->select('*')->where('cat_id', $id)
->where('sub_status', '1')->orderBy('sub_id', 'asc')->get();
$name = DB::table('category')->where('cat_id', $id)->get();
return view('buy-and-sell/grid', compact('r','name','count'));
}
image for your help
image for your help
problem in this image please solve the problem
Although its no good Practice Accessing the DB in Blade (better do this in the controller and pass the data) you can do:
<div class="price"><strong>Products</strong>
<span>
{{ BasicModel::where('sub_id', $row->sub_id)->count() }}
</span>
</div>
Its not tested, but have a look at the Eloquent docs, the count() method is explained there.
Update: I am not shure if laravel will find the class BasicModel (I never would access Models directly in blade, as stated do this in the controller and pass the data.) So maybe you need to write it with the full Namespace most likely {{ \App\BasicModel::where() }}.

Categories