How to skip null collection inside array when doing a foreach - laravel

I have an array of collection like this:
array:2 [▼
0 => Illuminate\Support\Collection {#1401 ▼
#items: []
#escapeWhenCastingToString: false
}
1 => Illuminate\Support\Collection {#1405 ▼
#items: array:4 [▼
0 => {#1407 ▼
+"id": "887923fe-1993-4e5b-8a99-699d66be129c"
+"employee_id": "887923fe-1993-4e5b-8a99-699d66be129c"
+"in_time": "2022-01-10 11:31:44"
There's a null #items: inside it. And whenever I'm trying to loop the data, I always got error property not exist. I know it because the first collection item in my array is null. But I don't know how to skip it.
I've tried to use isNotEmpty(), but still got the error
#foreach ($attendance as $data)
#if ($data->isNotEmpty())
<td>{{ $data->name ?? '' }}</td>
<td>{{ $data->alias ?? '' }}</td>
...

You can use 2 approach.
First, checking null data in loop by counting the array
// Blade
#foreach ($attendance as $data)
#if (count($data) > 0)
<td>{{ $data->name ?? '' }}</td>
<td>{{ $data->alias ?? '' }}</td>
...
#endif
#endforeach
Or, checking in database with Eloquent method whereNotNull, so null data will not appear in your blade variable
// Eloquent
Model::whereNotNull('column_name')
Laravel 8.x, Database: Query Builder, additional-where-clauses

Use #if to check for NULL
#foreach ($attendance as $data)
#if (!empty($data))
<td>{{ $data->name ?? '' }}</td>
<td>{{ $data->alias ?? '' }}</td>
...

Related

Laravel 7: Match two column dates with current date and show value depends on the condition

Leave:
id
user_id
start_date
end_date
1
2
2022-06-01
2022-06-03
Blade:
#foreach ($users as $row )
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $row->id }}</td>
<td>{{ $row->name }}</td>
<td>{{ $row->dpt->department }}</td>
#php
$today = Carbon\Carbon::now();
$leave = App\Leave::where('user_id', $row->id)->whereBetween('') <!-- incomplete -->
#endphp
<td>Leave Status</td>
</tr>
#endforeach
In this table, all user lists are shown. Here in the Leave Status column, it will show On Leave if the user is on leave today. I think I have to match today's date with start_date and end_date of the leave table and also match the user_id
What will be the eloquent query for this?
Example:
id
name
Leave Status
1
Jhon
Present
2
Doe
On Leave
3
Laura
On Leave
If you also have the relationships defined in the model you could load them with constraints in your controller:
$users = User::with(['leaves' => function ($query) {
$query->where('start_date', '>=', Carbon::now()))
->where('end_date', '<=', Carbon::now()));
}])->get();
This way you don't have to query in your blade templates and you can just check if count($row->leaves) > 0
have you try this:
\Carbon\Carbon::now()->between($row->leaves()->last()->start_date,$row->leaves()->last()->end_date) ? 'On Leave' : 'Present';

Foreach inside Foreach based on column value

I have an sql table knowledgebase like so
id , categoryid, title
id
categoryid
title
1
1
apple
2
1
fb
3
2
google
4
2
DB
5
3
Reebok
In my laravel blade, I am trying to create a tree view to look like the following
-1
--apple
--FB
-2
--google
--DB
-3
--Reebok
My controller does a basic query and returns the entire table to the view. I am a newbie to laravel so far, I can get a basic table to work like
#foreach($knowledgebase as $key => $value)
<tr>
<td>{!! $knowledgebase ->id !!}</td>
<td>{!! $knowledgebase ->title!!}</td>
<td>{!! $knowledgebase ->categoryid !!}</td>
</tr>
#endforeach
How would I iterate categroyid column , display first category and all child titles and then move on to the next categoryid.
Update
public function show($id) {
//get article
$knowledgebase = \App\Models\Knowledgebase::Where('knowledgebase_slug', request('knowledgebase_slug'))->first();
return view('knowledgebase', compact('knowledgebase'));
}
You will need to retrieve in controller the categories before ($categories)
#foreach($categories as $category)
<tr>
<td>{{ $category->id }}</td>
<td>{{ $category->title}}</td>
<td>{{ $category->categoryid }}</td>
</tr>
#endforeach
Anyways, I managed to solve this by adding a function children in my model. So in my Model added
public function children(){
return $this->hasMany('App\Models\Knowledgebase', 'categoryid');
}
After this, I simply called it as a foreach inside my foreach
#foreach($categories as $category)
<li>{{ $category->title}}</li>
#if($category->children)
#foreach($category->children as $child)
<ul>
<li class="pl-3"> {{ $child->title}} </li>
</ul>
#endforeach
#endif
#endforeach

Laravel: How can I use Group By in laravel blade?

I am trying to get all slots, then group them by room. Within my view, I want to have a row of the room:
<tr>
<td>Room ID 1</td>
<td>Slot ID 1</td>
<td>Slot ID 2</td>
<td>Slot ID 3</td>
.................
</tr>
<tr>
<td>Room ID 2</td>
<td>Slot ID 1</td>
<td>Slot ID 2</td>
<td>Slot ID 3</td>
.................
</tr>
I believe I am close, but not sure of the "Laravel way". The data looks good - as in, the query is getting/grouping correctly, I think my struggle is understanding how to loop through the collection.
MyController.php
public function routineViewDayWise()
{
$sunday_routines = Routine::where('day_id', 1)->orderBy('room_id')->get()->groupBy('room_id');
return view('day_wise_routine', compact('sunday_routines'));
}
In my view I can see I am getting this:
MyView.blade.php
#items: array:4 [▼
2 => Illuminate\Database\Eloquent\Collection {#1323 ▼
#items: array:2 [▼
0 => App\Models\Routine {#1339 ▶}
1 => App\Models\Routine {#1340 ▶}
]
}
4 => Illuminate\Database\Eloquent\Collection {#1322 ▶}
6 => Illuminate\Database\Eloquent\Collection {#1336 ▶}
8 => Illuminate\Database\Eloquent\Collection {#1335 ▶}]
SOLUTION
Here is what my view looks like to get the output I wanted.
MyView.blade.php
#foreach($sunday_routines as $room_id => $routines)
<tr>
<td>{{ $room_id }}</td>
#foreach($routines as $routine)
<td>{{ $routine->slot_id }}</td>
#endforeach
</tr>#endforeach
Hi friend please update the following as put groupBy() before get()
public function routineViewDayWise()
{
$sunday_routines = Routine::where('day_id', 1)->orderBy('room_id')->groupBy('room_id')->get();
return view('day_wise_routine', compact('sunday_routines'));
}

Accessing further data

So I am accessing an external API and I am trying to display this data
https://i.stack.imgur.com/Yop0I.png
and everything was fine so far as you can see
https://i.stack.imgur.com/L3hXq.png
using this code
<tr v-for="cv_output in cv_outputs" :key="cv_output.id">
<td>{{ 'teste' }}</td>
<td>{{ cv_output['id'] }}</td>
<td>{{ cv_output['last-modified-date'] }}</td>
<td>{{ cv_output['output-category']['value'] }}</td>
<td>{{ cv_output['output-category']['code'] }}</td>
<td>{{ cv_output['output-type']['value'] }}</td>
<td>{{ cv_output['output-type']['code'] }}</td>
<td>{{ cv_output['other-output'] }}</td>
but as soon as I try to go further such as
{{ cv_output ['other-output']['title'] }}
the data stops displaying in the table and in the console i get the following:
TypeError: Cannot read property 'title' of null
which doesn't make any sense I think. Any idea why?
Controller method:
public function getRemoteOutputs()
{
$science = Auth::user()->science_id;
$client = new Client(['headers' => ['Accept' => 'application/json']]);
$request = $client->get(
'https://url_to_the_api/'.$science.'/degree',
[
'auth' => ['client', 'secret'],
]
);
$data = $request->getBody()->getContents();
return $data;
}
I #Helpinghand is correct, one of the records is missing other-output.
Try:
<td>
<span v-if="cv_output['output-type']">{{ cv_output['output-type']['title'] }}</span>
<span v-else>No Output Type Title</span>
</td>
Try this:
{{ cv_output ['other-output'] ? cv_output ['other-output']['title']: ''}}
This will return the other-output->title if it exists, if not it should return nothing without error. (you can put whatever you want in the single quotes there if you want something like 'not available' as default)

Trying to pass data from controller to view in laravel 5

I am trying to pass 2 different columns from my sql table to my view ,so that i can show them.
My controller is:
$interface = DB::table("users")->distinct()->get(['name']);
$interfac = DB::table("users")->distinct()->get(['email']);
view()->share('users',compact('interface','interfac'));
My view is :
#foreach ($users as $key => $value)
<tr>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
</tr>
But this is not working while passing the two variables.If i pass one it is working but passing two is not working.thanks.
Controller
$users = DB::table('users')->get();
return view('users', compact('users'));

Resources