what's wrong with my foreach in laravel? - php

I'm going to pass data in array
but here's the code
public function test($pid){
$row_for_menu = Menu::where('parent_id', '=', $pid)->get();
$menu = array();
foreach ($row_for_menu as $menu_one_by_one){
$menu[] = array('title' => $menu_one_by_one->name, 'nodes' => $this->test($menu_one_by_one->id));
}
dd($menu);
}
public function index(Request $request)
{
$this->test(1);
//$perPage = 25;
//$menu = Menu::paginate($perPage);
//return view('admin.menu.index', compact('menu'));
}
my foreach in first round worked well
but in the end responsed [ dd($menu) ] empty array and error 500 !
my english is not well sorry ;)

try this demo working fine
public function test($pid){
$row_for_menu = Menu::where('parent_id', '=', $pid)->get()->lists('id','name');
$menu = array();
//foreach ($row_for_menu as $menu_one_by_one){
//$menu[] = array('title' => $menu_one_by_one->name, 'nodes' => $this->test($menu_one_by_one->id));
//}
dd($menu);
}

$menu is empty ie. array() , because $row_for_menu is empty
public function test($pid){
$row_for_menu = Menu::where('parent_id', '=', $pid)->get();
$menu = array();
foreach ($row_for_menu as $menu_one_by_one){
$menu[] = array('title' => $menu_one_by_one->name, 'nodes' => $this->test($menu_one_by_one->id));
}
if(count($menu)){
dd($menu);
}
}
public function index(Request $request)
{
$this->test(1);
//$perPage = 25;
//$menu = Menu::paginate($perPage);
//return view('admin.menu.index', compact('menu'));
}

You should define a relation between your menu items on the model instead of recursively looping to build the menu.
// Menu model
public function parent ()
{
return $this->belongsTo(__CLASS__, 'parent_id');
}
public function children ()
{
return $this->hasMany(__CLASS__);
}
Then in your view:
#foreach ($menu->children as $child)
// $child->name
// $child->link
#endoreach
Your controller would simply be:
// assuming you pass a menu id for specific page or similar
public function index(Request $request) {
$menu = Menu::find($request->getAttribute('menu_id'))->toArray();
return view('admin.menu.index', compact('menu'));
}

the test function must return $menu after foreach like this
public function test($pid){
$menus = Menu::where('parent_id', '=', $pid)->get();
$menu = array();
foreach ($menus as $menu_one_by_one){
$menu[] = array('text' => $menu_one_by_one->name, 'nodes' => $this->test($menu_one_by_one->id));
}
return $menu;
}
public function index(Request $request)
{
$x = $this->test(1);
dd($menu)

Related

Complex query and getting results by slug instead of ID in laravel

I have complex query and relation which I'm not fully understand. I'm kind of new in Laravel. Anyway, I'm looking for a way to load this with slugs instead of ID's.
This is the function in the controller
public function index( $category_id)
{
$Category = new Category;
$allCategories = $Category->getCategories();
$category = Category::find($category_id);
if($category->parent_id == 0) {
$ids = Category::select('id')->where('parent_id', $category_id)->where('parent_id','!=',0)->get();
$array = array();
foreach ($ids as $id) {
$array[] = (int) $id->id;
}
$items = Item::whereIn('category_id',$array)->where('published', 1)->paginate(5);
} else {
$items = Item::where('category_id' ,$category_id)->where('published', 1)->paginate(5);
}
return view('list', compact('allCategories','items'));
}
Those are relations in the Model
public function item()
{
return $this->hasMany('App\Item','category_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function getCategories()
{
$categoires = Category::where('parent_id',0)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function selectChild( $id )
{
$categoires = Category::where('parent_id',$id)->where('published', 1)->paginate(40);
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function addRelation( $categoires )
{
$categoires->map(function( $item, $key)
{
$sub = $this->selectChild($item->id);
$item->itemCount = $this->getItemCount($item->id , $item->parent_id );
return $item = array_add($item, 'subCategory', $sub);
});
return $categoires;
}
public function getItemCount( $category_id )
{
return Item::where('category_id', $category_id)->count();
}
This is what I have in my routes
Route::get('list/{category}', 'ListController#index')->name('list');
currently is loading urls like http://example.com/list/1 where 1 is the ID. I'm wonder if with current setup is possible to make it like, http://example.com/slug
I'm aware how slugs are working. I just can't understand how to use them in queries instead of ID's
You can use explicit Route Model Binding to grab your Category by slug before processing it.
In your RouteServiceProvider you need to bind the model:
Route::bind('category', function ($value) {
//Change slug to your column name
return App\Category::where('slug', $value)->firstOrFail();
});
Then, you can typehint the categories.
For example in your index method:
public function index(Category $category)
{
$Category = new Category;
$allCategories = $Category->getCategories();
//This line is obsolete now:
//$category = Category::find($category_id);
//...
}
Try to change your index function parameter from $category_id to $category_slug
Remove this line $Category = new Category;
And change this $category = Category::find($category_id);
To this: $category = Category::where('slug', $category_slug)->first();
*Assuming that you have a unique slug in category table

Laravel filters system with multi checkbox

I am using laravel 5.4 and I want to filter search. its my front-end
my code looks like this
class DeviceFilterController extends Controller
{
public function filter(Feature $feature){
$marks = isset($_POST["mark"]) ? $_POST["mark"] : null;
$feature = $feature->newQuery();
if(isset($marks ))
{
foreach ($marks as $value)
{
$feature->where('device_mark', $value);
}
}
return $feature->get();
}
}
that result just one entry
You could take a different approach using whereIn(), assuming you mark input is an array of IDs like [1, 4, 8, 22].
public function filter(Request $request)
{
$features = Feature::when($request->has('mark'), function($query) use ($request) {
return $query->whereIn('device_mark', $request->mark); //Assuming you are passing an array of IDs
})->get();
return $features;
}
when() closure will only executes when you are sending 'mark' input. Doing it without when would look like this
public function filter(Request $request)
{
$features = [];
if ( $request->has('mark') && $request->mark != '' ) {
$features = Feature::whereIn('device_mark', $request->mark)->get();
} else {
$features = Feature::get();
}
return $features;
}

how to do this in Laravel 5.2

I have 2 public function in My Controller
public function index()
{
$projects = Project::personal()->get();
return view('projects.index')->withProject($projects);
}
other one is
public function show($id) {
$project = Project::find($id);
$tasks = $this->getTasks($id);
$files = $this->getFiles($id);
$comments = $this->getComments($id);
$collaborators = $this->getCollaborators($id);
return view('projects.show')->withProject($project)->withTasks($tasks)->withFiles($files)->withComments($comments)->withCollaborators($collaborators);}
I need get
$collaborators = $this->getCollaborators($id);
to My public function index() method to print collaborators in ('projects.index') view
how can do this?
Update your index function with this code, haven't tested it
public function index()
{
$projects = Project::personal()->get();
foreach($projects as $key => $project) {
$find = Project::find($project->id);
$tasks = $this->getTasks($project->id);
$files = $this->getFiles($project->id);
$comments = $this->getComments($project->id);
$collaborators = $this->getCollaborators($project->id);
$projects[$key]['collaborators'] = $collaborators;
}
return view('projects.index')->withProject($projects);
}
In ('projects.index') you will have collaborators value for each database record

Custom Query in Cakephp 3.0?

I want to make a custom query in Cakephp. I've been reading this: Query Builder
The problem that every example are like:
$query = $articles->find()
->where([
'author_id' => 3,
'OR' => [['view_count' => 2], ['view_count' => 3]],
]);
But in my PostController I have this:
public function view($id = null)
{
$post = $this->Posts->get($id, [
'contain' => ['Users']
]);
$this->set('post', $post);
$this->set('_serialize', ['post']);
}
I don't have anything with find(). And I don't know what is doing the last part of code
This is the query that I want to use:
public function index()
{
$query = $posts->find()->where([
'userfk' => 1
]);
}
But it isn't working, I don't know how to display the query result.
How can I have the code to working right?
Thanks!
If you want use Query Builder
http://book.cakephp.org/3.0/en/orm/query-builder.html
PostsController.php
public function index() {
$posts = $this -> Posts -> find() -> where(['userfk' => 1]);
$this -> set('post', $posts);
}
By the way, if the result get few $posts
Your set should be $this -> set('posts', $posts); and your view have
<?php foreach($posts as $post): ?>
<!-- your code -->
<?php endforeach; ?>
///////
EDIT
Adding Paginator option
PostsController.php
public function index() {
$this -> paginate['contain'] = ['Users'];
$this -> paginate['conditions'] = ['Posts.userfk' => 1];
$this -> set('posts' , $this -> paginate($this -> Posts));
}
public function index()
{
$query = $posts->find()->where([
'userfk' => 1
]);
//or you can use dynamic finders
$query = $posts->findByUserfk(1);
$this->set('post', $query);
}
in your view. print all result;
pr($post);
or you can use foreach to iterate the result
foreach($post as $i => $val) {
echo $val->userfk;
}
Load Model before use in function
Please use in controller
public function initialize() {
parent::initialize();
$this->loadModel('Posts');
}
Then Index function:-
public function index()
{
$posts = $this->Posts->find('all', ['conditions' => ['userfk' => 1]]);
$this->set('posts',$posts);
//pr($posts->toArray());// Print Posts array
}
I do not understand why do you pass $pots in( $query = $posts->find()).
public function index()
{
$posts = $this->Post->find('all', ['conditions' => ['userfk' => 1]]);
$this->set('post', $posts );
//print_r($posts);you can print array.
}

laravel eloquent : Increments visits column by one for every visits

I have model for my post in my site.My post model has a column that stores visits.when user visit my post should increments by 1.
I exactly knows how to do this, but my problem is when I increment it by one in my model, it's increments by 2!!!!!
I wrote this code in my controller:
$new_post_inst = Post::where('id','=',$id)->first();
$new_post_inst->increment('visit');
This is my controller:
public function get_id($id) {
// cat
$cat = Category::join('catrelations', 'catrelations.idcat', '=', 'categories.id')->orderBy('categories.id', 'ASC')->get();
// menu
$nav = Nav::orderBy('index', 'DESC')->get();
$post = Post::find($id);
$setting = Settings::find(1);
$comments = Comment::where('post_id', '=', $id)->orderBy('id', 'asc')->get();
$get_reply = array();
$get_reply_id = array();
//$counter = 0;
//var_dump($comments);
foreach ($comments as $comment) {
$reply = Reply::where('parentId', '=', $comment->id)->get();
if (!$reply->isEmpty()) {
//$arr_reply[$comment->id] = $reply;
//echo $comment->id.' has reply!!!!!<br>';
//$reply_parent_id = $comment->id;
$counter = 0;
foreach ($reply as $replying) {
$get_reply[$comment->id][$counter] = Comment::where('id', '=', $replying->comment_id)->get();
//$comment_reply_id = $replying->comment_id;
//$reply_arr = array();
//$reply_arr[$comment->id] = $comment_reply_id;
//echo 'The reply is: '.$comment_reply_id.'<br>';
foreach ($get_reply[$comment->id][$counter] as $key => $value) {
//($value->text);
$get_reply_id[] = $value->id;
}
$counter++;
}
//$counter++;
}
}
$post_owner_info = User::select('id', 'first_name', 'last_name', 'image', 'desc')->find($post->user_id);
$arr = array();
$arr['comments'] = $comments;
$arr['post'] = $post;
//$arr['reply'] = $reply;
//var_dump($get_reply);
//var_dump($get_reply_id);
$new_post_inst = Post::where('id','=',$id)->first();
$new_post_inst->increment('visit');
return View::make('blogsingle', compact('arr'))->with('setting', $setting)->with('post', $post)->with('nav', $nav)->with('get_reply', $get_reply)->with('get_reply_id', $get_reply_id)->with('cat', $cat)->with('post_owner_info', $post_owner_info);
}
And this is my Post model:
class Post extends Eloquent
{
public function User()
{
return $this->belongsTo('User');
}
public function Categories()
{
return $this->belongstomany('Category');
}
public function comments()
{
return $this->hasMany('Comment');
}
}
you can try like this
$new_post_inst = Post::where('id','=',$id)->first();
$new_post_inst->increment('visit',1);
Try this:
$new_post_inst = Post::where('id','=',$id)->first();
$new_post_inst->visit+=1;
$new_post_inst->save();
OR this:
$new_post_inst = Post::where('id','=',$id)->first();
$new_post_inst->update(array('visit' => $new_post_inst->visit+1));
I searched around for a little bit and this could be the favicon icon that is making a second request. How did you declare the favicon? Or maybe you could remove it to try and see if it is indeed the favicon?

Categories