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

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'));
}

Related

I want to count total yes against an id in a particular row not a column

I want to sum total yes in a row like following
id
user_id
eligible
asset
requirement
1
1
yes
no
yes
2
1
yes
yes
yes
3
2
no
yes
no
Result should be following:
user_id
yes_count
1
5
2
1
I consider that table as Items.
User model
public function items()
{
return $this->hasMany(Item::class);
}
Controller
$users = User::withCount([
'items as items_eligible_yes_count' => fn($q) => $q->where('eligible', 'yes'),
'items as items_asset_yes_count' => fn($q) => $q->where('asset', 'yes'),
'items as items_requirement_yes_count' => fn($q) => $q->where('requirement', 'yes'),
])
->get();
View
<table>
<thead>
<tr>
<th>user_id</th>
<th>yes_count</th>
</tr>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->items_eligible_yes_count + $user->items_asset_yes_count + $user->items_requirement_yes_count }}</td>
</tr>
#endforeach
</tbody>
</table>

not able to show array in Table #foreach

I am new to Laravel and coding. Trying to show Month name (Array) in table but not able to do the same. I tried few things like "json_encode" but got error each time.
My controller code is
$months = array();
for ($i = 0; $i < 12; $i++) {
$timestamp = mktime(0, 0, 0, date('n') - $i, 1);
$months[date('n', $timestamp)] = date('M-Y', $timestamp);
}
Output is
array:12 [▼
3 => "Mar-2022"
2 => "Feb-2022"
1 => "Jan-2022"
12 => "Dec-2021"
11 => "Nov-2021"
10 => "Oct-2021"
9 => "Sep-2021"
8 => "Aug-2021"
7 => "Jul-2021"
6 => "Jun-2021"
5 => "May-2021"
4 => "Apr-2021"
]
View file
<table id="incometable" class="table m-0 table table-bordered table-hover table" data-order='[[ 0, "desc" ]]'>
<thead>
<tr>
<th align="center">Month</th>
<th>Milk Sale Amount (Rs.)</th>
<th>Animal Sale Amount (Rs.)</th>
<th>Other Sale Amount (Rs.)</th>
</tr>
</thead>
<tbody>
#foreach ($months as $item )
<tr>
<td>{{ $item->$months }}</td>
</tr>
#endforeach
</tbody>
</table>
Thanks in Advance
During your #foreach() loop, $item is not an Object, it is a String 'Mar-2022' through 'Apr-2021'. You need to adjust your code:
#foreach($months as $key => $label)
<tr>
<td>{{ $label }}</td>
<tr>
#endforeach
If you need the 1 through 12 values, they are available in each iteration as $key.

How to skip null collection inside array when doing a foreach

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>
...

validation using required_with in laravel for input filed as array?

i have a table with checkbox as array and textbox as also array. what i want to achieve is when the user checked a checkbox it should validate that input textbox are not be empty.
public function roombooking(Request $request)
{
$messsages = array(
'check.required'=>'No room was selected.Please select room to proceed for booking !',
'txtnos.required|numeric'=>'Please enter no of persons',
);
$rules = array(
'check'=>'required',
'txtnos'=>'required_with:data', //txtnos is a array input filed and data is a array checkbox
);
$validator = Validator::make($request->all(), $rules,$messsages
);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withinput();
}
}
Html code
<table class="table table-hover" data-toggle="table" id="table"
data-click-to-select="true">
<thead>
<tr>
<th style="width:10%;" data-field="ActivityId">Select</th>
<th style="width:30%;" data-field="ActivityName">Activity Name</th>
<th style="width:30%;" data-field="Rate">Rate/Person</th>
<th style="width:30%;">Nos. of person</th>
</tr>
</thead>
<tbody>
#foreach($loadactivity as $key=>$activity)
<tr>
<td>
<input type="checkbox" name="data[]" value="0;{!! $activity->ActivityId !!};{!! $activity->Rate !!};0;0;{!! $activity->ActivityName !!}" />
</td>
<td>{!! $activity->ActivityName !!}</td>
<td>{!! $activity->Rate !!}</td>
<td >{!! Form::text('txtnos[]','',['class' => 'form-control small-textbox ','txtnoid'=>$activity->ActivityId]) !!}</td>
</tr>
#endforeach
</tbody>
</table>
please help me
Change your form:
...
<td><input type="checkbox" name="row[{{$key}}][data]" value="0;{!! $activity->ActivityId !!};{!! $activity->Rate !!};0;0;{!! $activity->ActivityName !!}" />
</td>
<td>{!! $activity->ActivityName !!}</td>
<td>{!! $activity->Rate !!}</td>
<td>{!! Form::text('row[{{$key}}][txtnos]','',['class' => 'form-control small-textbox ','txtnoid'=>$activity->ActivityId]) !!}</td>
...
So the only thing that's changed is the name of data and txtnos, it will give you the following:
$exampleResult = [
'row' => [
// old $key as new key
0 => [
'txtnos' => 'entered value',
'data' => '1', // But only if checked
],
1 => [
'txtnos' => 'entered value',
'data' => '1', // But only if checked
],
]
];
Validation rules
$rules = [
'row.*.txtnos' => 'required_with:row.*.data'
];
In the example, txtnos on each row is required if data on the same row isset.
Validation message
$messages = [
'row.*.txtnos.required_with' => 'Enter a value or uncheck the checkbox..'
];
Important:
The validation for .*. was added in Laravel 5.2, you didn't specify your exact version so I'm not sure if it will work for you. Anyway, there is another way to do this.
For versions < 5.2, loop the input rows and replace the * in my example with the current key.

Laravel5.1, Relation, EloquentORM, Many to Many, Sort

<table border="true">
<tr>
<th style="width:100px">Table</th>
<th colspan="3" style="width:300px">Columns</th>
</tr>
<tr>
<td style="width:100px">Articles</td>
<td style="width:100px">id</td>
<td colspan="2" style="width:200px; color: #aaaaaa">other dependent variables</td>
</tr>
<tr>
<td style="width:100px">Article_Tag</td>
<td style="width:100px">id</td>
<td style="width:100px">article_id</td>
<td style="width:100px">tag_id</td>
</tr>
<tr>
<td style="width:100px">Tags</td>
<td style="width:100px">id</td>
<td style="width:100px">name</td>
<td style="width:100px"></td>
</tr>
</table>
Then, I want to sort Articles table by [name] of Tags table.
I tried eager-loading with closure below, but it did'nt work.
Model Article and Tag are connected with each other just by belongsToMany,
and I succeed in output their data, but they weren't sorted.Offcourse, I did'nt give getTag any argument.(When I gave argument, they weren't narrowed by [name] either.)
use App\Article;
use App\Tag;
...
public function __construct(Article $article)
{
$this->article = $article;
}
...
public function getTag($tag = NULL)
{
$flag = isset($tag);
$articles = $this->article->orderBy('created_at', 'desc')->with([
'tags' => function($query) use ($flag, $tag){
($flag)
? $query->where('name', $tag)
: $query->orderBy('name');
}
])->paginate(15);
Try this variant:
$articles = $this->article->with([
'tags' => function($query) use ($flag, $tag){
return $flag
? $query->where("name", $tag);
: $query->orderBy("name")
}
])->paginate(15);

Resources