how to display data from self created array in laravel? - php

I create an array for the blade view. Collect the data from table and store in an array, $post_data. For laravel generated array, foreach loop will do the job. But, it seems a different things with self created array. Please help.
I use 2 foreach because the array consist of 2 dimensional array.
The result of dd($post_data)
The result of var_dump($data)
The result of var_dump($item)
ERROR: Trying to get property 'title' of non-object
Controller
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM)
{
$post = post::find($RMM->id);//get post for each department
if (isset($post))
{
$post_data[] = array('title' => $post->article_title,
'name' => $RMM->department.'#'.$post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
}
}
Blade
#foreach($post_data as $key => $data)
#foreach ($data as $item)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $item->title }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $item->name }}
# {{$item->department}}</a>
</div>
#endforeach
#endforeach
Company
```migrations```
Schema::create('companies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('department');
$table->string('branch');
$table->timestamps();
});
Post
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('company_id');
$table->string('event_title')->nullable();
$table->string('article_title')->nullable();
$table->string('date');
$table->string('author')->nullable();
$table->string('article')->nullable();
$table->string('description')->nullable();
$table->string('file')->nullable();
$table->string('banner_image')->nullable();;
$table->string('gallery_image')->nullable();
$table->index('user_id');
$table->index('company_id');
});

The problem is you are tying to access a property of a NON OBJECT as the error says.
item is not an object, it's an array.
so you have to use the array access method to access its values.
#foreach($post_data as $key => $data)
#foreach ($data as $item)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $item['title'] }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $item['name'] }}
# {{$item['department'] }}</a>
</div>
#endforeach
#endforeach
UPDATE
Looking at the dump of the $post_data realized that you don't have to loop each element of the array again.
#foreach($post_data as $key => $data)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $data['title'] }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $data['name'] }}</a>
</div>
#endforeach

If you just want get the title, name and date it's simple
Controller
post_data = Array();
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM)
{
$post = post::find($RMM->id);//get post for each department
if (isset($post))
{
$post_data[] = array(
'title' => $post->article_title,
'name' => $RMM->department.'#'.$post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
}
}
// You can send a array of objects
return view('example')->with('posts', $post_data);
View
#foreach($posts as $post)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $item['title'] }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $item['name'] }}
# {{$item['department']}}</a>
</div>
#endforeach

I correct it. Thank you for all the comments and advice. Here is how I do it.
The $post_data[] is correct since I need to store a lot of return result from find function. Since, find already return an array of corresponding id, I do not need to put into another array, just use it as it is, as explain by #Ghost. Thus, one foreach enough to get the job done.
Controller
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM)
{
$post = post::find($RMM->id);//get post for each department
if (isset($post))
{
$post_data[] = $post;
}
return view('home')->with('posts', $post_data);
}
Blade
#foreach($posts as $post)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $item['title'] }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $item['name'] }}
# {{$item['department']}}</a>
</div>
#endforeach

Update answer
Another method, is to convert the array into object. The error is about non-object, directly working on it would help.
ERROR: Trying to get property 'title' of non-object.
Alternative way
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM)
{
$post = post::find($RMM->id);//get post for each department
if (isset($post))
{
$post_data[] = array('title' => $post->article_title,
'name' => $RMM->department.'#'.$post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
}
}
//change to object before send to blade
$object = json_decode(json_encode($post_data), FALSE);
return view('home')->with('posts', $object);

Related

(Laravel 9) Foreach Loop is showing multiple items for one row of data and not showing other data in one view

So I have this problem with my Laravel project that I'm working on right now when I'm trying to store one data to the database but in the view, it shows five of it. And whenever I add another data. It won't stack. Kind of confusing, ain't it?
So What I'm actually trying to do is that I have 2 Models and is trying to overlap them to each other. As I search for ways to make them show in one view, I concluded in putting them into one Controller.
I made their Store CRUD separate so that it would work and this is how it looks like:
public function groupStore(Request $request)
{
$request->validate([
'title'=>'required',
'subject'=>'required',
'section'=>'required',
'team'=>'required',
'advisor'=>'required',
]);
GroupProject::create($request->all());
return redirect()->back()->with('success', 'Created Project Successfully.');
}
public function projectStore(Request $request)
{
$request->validate([
'title'=>'required',
'file'=>'required',
'description'=>'required',
]);
$file = $request->file('file');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move(public_path('files'), $fileName);
$data = array(
'title'=>$request->title,
'file'=>$fileName,
'description'=>$request->description
);
Project::create($data);
return redirect()->back()->with('success', 'Posted Project Successfully.');
}
And here is how the Show CRUD looks like:
public function show(GroupProject $group_projects, Project $projects, $id)
{
$group_projects = GroupProject::find($id);
$projects = Project::find($id);
if (auth()->user()->type == 'faculty') {
return view('faculty/project', compact(['group_projects', 'projects']));
}else if (auth()->user()->type == 'office') {
return view('office/project', compact(['group_projects', 'projects']));
}else{
return view('student/project', compact(['group_projects', 'projects']));
}
}
PS: I'm trying to have Three users which makes the if else statements.
Now here's where the real problem comes from. As I make the "Group Project", I made the view with a foreach loop in order to show everything from my datastore, such as this and the corresponding program for it looks like this:
#foreach($group_projects as $key => $groupProject)
<div class="col flex">
<div class="card h-100">
<div class="card-body">
<h3 class="card-title">{{ $groupProject->title }}</h3>
<h6>{{ $groupProject->subject }}</h6>
<h6>{{ $groupProject->section }}</h6>
<h6>{{ $groupProject->team }}</h6>
<h6>{{ $groupProject->advisor }}</h6>
<div class="dropdown">
<button id="dropdownMenu" class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ __('Actions') }}
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu">
<li><a class="dropdown-item" href="{{ URL::to('project/' . $groupProject->id) }}">
{{ __('Show')}}
</a></li>
</ul>
</div>
</div>
</div>
</div>
#endforeach
On this case, there seems to be no problem at all and it works perfectly fine even if I try to add another one.
But as I try to click it and change the view, this would be how it looks like after storing a "Project" and here's its corresponding Code:
#if (is_array($projects) || is_object($projects))
#foreach($projects as $key => $project)
<div class="col flex my-2">
<div class="card">
<div class="card-body">
<h3 class="card-title">{{ $projects->title }}</h3>
<iframe src="/files/{{ $projects->file }}"></iframe>
<h6>{{ $projects->description }}</h6>
</div>
</div>
</div>
#endforeach
#endif
And after adding another "Project" it will not show up on the "Test Title 1" but instead in "Test Title 2" which is pretty frustrating.
At first I'm thinking that it might be because I made the if statement of "#if (is_array($projects) || is_object($projects))" but if I remove this part, it would show an error when I'm trying to view a "Group Project" While there's nothing in the "Project" yet.
Another is that after making the foreach loop "#foreach($projects as $key => $project)" , I still call the "$projects->title" instead of "$project->title". but the reason for this is that it shows an error of "Attempt to read property "title" on bool".
I wonder, what should I do?
EDIT:
Nevermind Guys, I actually solved it just now.
So the real problem was on my Show CRUD. Instead of listing it as
$group_projects = GroupProject::find($id);
$projects = Project::find($id);
I should've called it as
$group_projects = GroupProject::find($id);
$projects = Project::all();
And Everything will be solved lol..... Now my problem is how to overlap them into one another such as 1 "Group Project" can have multiple "Project"....

Recursive system : load all products in each categories

I've made this system with the help of Staudenmeir\LaravelAdjacencyList.
It's a recurcive system to load categories, with their products for each.
The moment where I fail (I think) is when loading the products. Because his module duplicates a request and I don't think that's normal ?
the view :
`
#foreach($products as $product)
<article class="article-small">
<a href="{{ route('product.index', array($product->id, $product->productCat->slug, $product->slug)) }}">
<header>
<img src="{{ asset('uploads/products/'.$product->img.'')}}" alt="{{ $product->product_name }}"/>
<p>{{\Illuminate\Support\Str::limit($product->description, 70, '...')}}</p>
</header>
<section class="d-flex justify-content-between">
<div class="left">
<h3 title="{{$product->product_name}}">{{$product->product_name}}</h3>
</div>
#if($product->product_price != '')
<span class="price"><b>{{$product->priceRender()}} €</b></span>
#else
<span class="price"><b>{{$product->product_total_price}} €</b></span>
#endif
</section>
</a>
</article>
#endforeach
`
The Controller :
`
public function getById($locale, $id)
{
$category=$this->productCatManagement->getById($id);
$query=$this->productCatManagement->allProductsByParent($category);
$ariane = $this->productCatManagement->getAriane($category, "catPage");
return view('product.productCat.get-by-id', compact('category', 'query', 'ariane'));
}
`
allProductsByParent function :
`
$categories = $parent->descendantsAndSelf()->get();
$stockProducts = collect([]);
foreach($categories as $category)
{
$products = $category->products->where('state', '=', '1');
$products->each(function($product) use ($stockProducts){
$stockProducts->push($product);
});
}
return $stockProducts;
`
Do you think i'm doing right ?
Picture of the requests : Here
I except a system with less of request as possible.
Thank you by advance all !

Laravel, get nested array

So, this is my json format data
{
"New Purchase Orders Created":{
"date":"2018-02-26 14:05:14.000000",
"timezone_type":3,
"timezone":"UTC"
},
"colour":"bg-primary"
}
This is my view in blade.php
<ul class="list-group list-group-flush">
#foreach( $notifications as $notification )
<?php $notificationData = json_decode($notification->data, true);?>
#foreach( $notificationData as $key=>$item )
<li class="list-group-item text-white {{ $notificationData['colour'] }}">
#if ($key!='colour')
{{ $key }}<br>
{{ $item['date'] }}
#endif
</li>
#endforeach
#endforeach
</ul>
I want to get the data into the blade. So what should I do?
This is what i want to get.
Please help. Thanks.
Assuming the above JSON is an object array like this:
<?php
$notifications = '[{
"New Purchase Orders Created":{
"date":"2018-02-26 14:05:14.000000",
"timezone_type":3,
"timezone":"UTC"
},
"colour":"bg-primary"
},
{
"New Purchase Orders Created":{
"date":"2018-02-26 14:05:14.000000",
"timezone_type":3,
"timezone":"UTC"
},
"colour":"bg-primary"
}]';
?>
Thus, the script will be like this:
<ul class="list-group list-group-flush">
#foreach( json_decode($notifications, true) as $notification => $data )
<?php $item = $data[key($data)]; ?>
<li class="list-group-item text-white {{ $data['colour'] }}">
{{ key($data) }}<br>
{{ $item['date'] }}
</li>
#endforeach
</ul>
Use json_decode. This works with JSON you've shown:
{{ json_decode($json, true)['New Purchase Orders Created']['date'] }}
If New Purchase Orders Created key may be different in every JSON, use the array_first() helper:
{{ array_first(json_decode($json, true))['date'] }}
If you will have many elements, iterate over them:
$array = json_decode($json, true);
#foreach ($array as $key => $element)
{{ $array[$key]['date'] }}
#endforeach

array to string conversion in laravel

I am trying to fetch some data from table in laravel 5.0 like so
public function index()
{
$data = DB::table('modules')->get();
return view("BaseView.home")->with('data',$data);
}
this is my view
#foreach($data as $modules)
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ $modules->module_name }}<i class="plusMinus fa fa-plus-square plusMinusSpacing" aria-hidden="true"></i>
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
{!! $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get() !!}
#foreach($moduleCategories as $category)
<a class="dropdown-item" href="#">{{ $category->categories_name }}</a>
#endforeach
</div>
</li>
#endforeach
$module->id is obtained from another query result. Now when I try to run this I am getting Array to string conversion. Can someone point out the mistake. The expected output is > 1 in the sense there can be multiple categories names matching that condition.
The problem is that you are trying to put php logic inside an echo {{ ... }}. You are trying to echo out a collection or an array of data, hence the error you are getting, Array to string conversion. The proper way to do this is to do the logic in the controller. But for a quick fix, replace:
{!! $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get() !!}
to
<php $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get(); ?>
Never use {{ ... }} or {!! ... !!} to put logic, those are to echo out a string.
==EDIT==
I suggest to use laravels eloquent relationship methods, this will simplify the code, and seperate the logic from the view.
Note: Expecting if you are using laravel naming convention.
On your Modules model, add a relationship to ModuleCategory like so:
public function module_categories()
{
return $this->hasMany('App\ModuleCategory');
}
On your controller, on the index method replace :
$data = DB::table('modules')->get();
with
$data = Modules::get();
and finally on the view, change it like so:
#foreach($data as $modules)
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ $modules->module_name }}<i class="plusMinus fa fa-plus-square plusMinusSpacing" aria-hidden="true"></i>
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
#foreach($modules->module_categories as $category)
<a class="dropdown-item" href="#">{{ $category->categories_name }}</a>
#endforeach
</div>
</li>
#endforeach
As I commented on Carlos's solution, here is how I solved the same error...
//Controller
$users = User::where('blah', 'blah')->get();
return view('index', [
'users' => $users,
]);
//View
<script type="text/javascript">
angular.module("app").factory("DataService", function() {
return {
users: {!! $users !!},
};
});
</script>
As discussed above, this will result in the Array to string conversion error, since $users is an array.
However, this error won't happen if $users is a `collection'
I.e.
//Controller
$users = User::all();
return view('index', [
'users' => $users,
]);
//This is ok
Or,
//Controller
$users = collect([]);
return view('index', [
'users' => $users,
]);
//This is fine too

How to loop through this array in Laravel?

I am working on a web application using laravel 5.3, I got one problem.
I want to loop through this array.
What I tried is:
Controller:
public function postSearch(Request $request)
{
$categoryid = $request->category_id;
$locationid = $request->location_id;
$category = Category::where('id', $categoryid)->first();
$cities = Location::where('id', $locationid)->pluck('city');
$cityname = $cities[0];
$alllocations = [];
$ratecards = [];
$locations = [];
$father = [];
$i = 0;
$filteredlocations = $category->locations->where('city', $cityname)->all();
foreach($filteredlocations as $location){
$alllocations[$i] = $location->getaddetails;
$ratecards[$i] = $location->ratecard;
$i++;
}
$father[0] = $alllocations;
$father[1] = $ratecards;
return view('ads', compact('father'));
}
View is here:
#foreach($father as $key => $f)
#foreach($f as $key => $arr)
#if (isset($arr->adName))
<div class="post">
{{Html::image($arr->path,'Ad Picture',array('class' => 'ad-image'))}}
<h2 class="post-title">{{ $arr->adName }}</h2>
<p class="description">{{ $arr->description }} </p>
<div class="post-footer">
<span class="categories">
<ul class="cats">
<li class="btn btn-default">Price :
{{ $f[$key]->monthly_rate }}
</li>
<li class="btn btn-default">Status:
#if($arr->status == 1)
<p>Active</p>
#else
<p>Not-Active</p>
#endif
</li>
<li>view details</li>
</ul>
</span>
</div>
</div>
#endif
#endforeach
#endforeach
Problem:
Okay problem is when I try to get {{ $f[$key]->monthly_rate }} which is the 2nd array i.e RateCards I get nothing. I want to get the Rate Card array and from that array mothly_rate which is a field in there.
Thanks
PS : {{ $f[$key]->monthly_rate }} this return nothings in view.
The problem is that $f[$key] is an array of two objects.
That means that the properties youre looking for are inside each of those items, like this:
$f[$key][0]->monthly_rate
$f[$key][1]->monthly_rate
You will have to loop those objects to get their properties values.

Categories