How to access map function in Laravel - laravel

This is my controller code:
public function RentCertificate()
{
$report = Report::distric()->status(1)->desk(15)->get()
->groupBy(function (Report $item) {
return $item->created_at->format('Y-m');
})
->map(function($rows, $key) {
return [
'column_one' => $rows->column_one,
'rows' => $rows
];
});
return view('adcr.report.rent_certificate', compact('report'));
}
when I try
#foreach($report as $key => $data)
<tr role="row" class="odd">
<td class="input_bangla">{{ $key+1 }}</td>
<td>{{ $data->fiscal_year }}</td>
<td>{{ $data->month }}</td>
</tr>
#endforeach
I got:
Property [fiscal_year] does not exist on this collection instance.
How can I access this data?

Here,
#foreach($report as $key => $data)
$data is the array you've mapped. An array like ['column_one' => ..., 'rows' => ...], it's not an object. You need to access one of its keys (column_one or rows).
Also, you can use a ternary operator with loop iteration to assign the classes even or odd in your <tr> element.
#foreach($report as $key => $data)
<tr role="row" class="{{ ($loop->iteration % 2) ? 'even' : 'odd' }}">
<td class="input_bangla">{{ $key+1 }}</td>
<td>{{ $data['rows']->fiscal_year }}</td>
<td>{{ $data['rows']->month }}</td>
</tr>
#endforeach

Related

Unique Data in Laravel

I have data like this
How to validate, if the user chooses same Kode, or user chooses a Kode that has conflicting Hari or Jam.
My Controller
public function store(Request $request)
{
$validate = Validator::make($request->all(), [
'kode_matkul' => 'required',
]);
if($validate->fails()) {
return response()->json(['errors' => $validate->errors()]);
}
}
My View Blade
<tbody>
#foreach ($mapel as $row)
<tr>
<td class="text-center">{{ $row->course }}</td>
<td>{{ $row->course_name }}</td>
<td class="text-center">{{ $row->sks }}</td>
<td class="text-center">{{ $row->kelompok }}</td>
<td>{{ $row->name }}</td>
<td class="text-center">{{ $row->hari }}</td>
<td class="text-center">{{ date('H:i', strtotime($row->start_time)) . ' - ' . date('H:i', strtotime($row->end_time)) }}</td>
<td class="text-center">{{ $row->ruangan }}</td>
<td class="text-center">
<input class="form-check-input" type="checkbox" name="kode_matkul[]" id="kode_matkul" value="{{ $row->course }}">
</td>
</tr>
#endforeach
</tbody>
Thank you
Please refer to https://laravel.com/docs/9.x/validation#form-request-validation for more information, but basically your steps would be -
create a store request for mapel (i guess?) with something like -
php artisan make:request StoreMapelRequest
In this newly create store request, you should create a rule for uniqueness to your desired fields -
public function rules()
{
return [
'Kode' => 'required|unique:mapels|max:255',
'Hari' => 'required|unique:mapels|max:255',
'Jam' => 'required|unique:mapels|max:255',
];
}
Edit: You can also add a simple |unique on your current store request, like this -
public function store(Request $request)
{
$validate = Validator::make($request->all(), [
'kode_matkul' => 'required|unique:mapels',
]);
if($validate->fails()) {
return response()->json(['errors' => $validate->errors()]);
}
}
Please notice that I assume that your table name is 'mapels', in which you are seeking this uniqueness rule.

Laravel year, sum, count, group by eloquent query

Can someone show me how I would build this query with eloquent, or is this required to be written with a DB:Raw query, or would it be best to be a raw sql query?
select `pay_week`,
year(`start_timestamp`) as year,
sum(`total_duration`) as 'duration',
count(`pay_week`) as 'entries'
from `time_clock`
group by year(`start_timestamp`),`pay_week`;
Any help to better understand would be greatly appreciated.
Thank you.
$entries = TimeClock::select(
'pay_week',
DB::raw('count(pay_week) as entries'),
DB::raw('YEAR(start_timestamp) as year'),
DB::raw('sum(total_duration) as duration')
)
->where('user_id', $user->record_id)
->sum('total_duration')
->groupBy('pay_week')
->get();
results in a
Call to a member function groupBy() on float
What I have now;
Blade;
<table class="table table-hover dataTable table-striped width-full" data-plugin="dataTable">
<thead>
<th>Pay Week</th>
<th>Date Range</th>
<th>Year</th>
<th>Total Hours</th>
<th>Gross Pay</th>
<th>Entries</th>
<th>Action</th>
</thead>
<tbody>
#foreach($entries as $group)
#foreach($group->entries as $entry)
#php
$week_start = (new DateTime())->setISODate(date("Y"),$entry->pay_week)->format("m/d");
$start = \Carbon\Carbon::createFromFormat("m/d", $week_start);
$end = $start->copy()->endOfWeek()->format('m/d');
$year = \Carbon\Carbon::parse($entry->start_timestamp)->format('Y');
#endphp
<tr>
<td>{{ $entry->pay_week }}</td>
<td>{{ $start->format('m/d') . ' - ' . $end }}</td>
<td>{{ $year }}</td>
<td>0</td>
<td>$ 0.00</td>
<td>0</td>
<td>[ Btn ]</td>
</tr>
#endforeach
#endforeach
</tbody>
</table>
This is what I have in the controller method.
$user = Auth::guard('user')->user();
$entries = TimeClock::select(
'pay_week',
'start_timestamp',
'total_duration'
)
->where('user_id', $user->record_id)
->get()
->groupBy('pay_week')
->map(function($entry) {
return (object)[
'count' => $entry->count(),
'duration' => $entry->sum('total_duration'),
//'year' => $entry->sum('start_timestamp')->year,
'entries' => $entry
];
});
return view('user.timeclock.reports.all', [
'entries' => $entries
]);
Given, that you set the cast in your model
class TimeClock extends Model
{
protected $cast = [
'start_timestamp' => 'datetime'
];
}
you can do the following:
$entries = TimeClock::select(
'pay_week',
'start_timestamp',
'total_duration'
)
->where('user_id', $user->record_id)
//->groupBy('pay_week')
->get()
->groupBy([ 'pay_week', function($entry) {
return $entry->start_timestamp->year
})
/*->map(function($entry) {
return (object)[
'count' => $entry->count(),
'duration' => $entry->sum('total_duration'),
'year' => $entry->start_timestamp->year,
'entries' => $entry
];
})*/;
You loop over it like this:
<table>
<thead>
<tr>
<th>Pay week</th>
<th>Date range</th>
<th>Year</th>
<th>Total hours</th>
</tr>
</thead>
<tbody>
#foreach($entries as $pay_week => $groups)
#foreach($groups as $year => $group)
<!--pay_week: {{ $pay_week }}<br />
count: {{ $group->count() }}<br />
duration: {{ $group->sum('total_duration') }}<br />
year: {{ $year }}<br />-->
<tr>
<td>{{ $pay_week }}</td>
<td></td>
<td>{{ $year }}</td>
<td>{{ $group->sum('total_duration') }}</td>
</tr>
#foreach($group as $entry)
#endforeach
#endforeach
#endforeach
</tbody>
</table>

How to fetch value from multiple table through pivot table in Laravel?

I'm trying to fetch value from different tables. I get the value but it repeat same quantity. I'm getting this see this image
I expect this see this image
Here is my controller code
$orders = Order::all();
view('admin.order.index', compact('orders'));
Here is my model relationship
return $this->belongsToMany(FoodItem::class, 'order_food_items', 'order_id', 'food_item_id')->withTimestamps();
}
public function orderItems() {
return $this->hasMany(OrderFoodItem::class);
}
public function user() {
return $this->belongsTo(User::class);
}
Here is in blade code, May be I'm doing wrong
#foreach ($orders as $key => $order)
#foreach ($order->orderFoodItems as $product)
#foreach ($order->orderFoodItemPrice as $price)
<tr>
<th scope="row">{{ $key + 1 }}</th>
<td>{{ $product->name }}</td>
<td>
<img src="{{ asset('/storage/items/food/' . $product->image) }}"
alt="">
</td>
<td>{{ $order->user->name }}</td>
<td>
<span class="badge badge-primary">Pending</span></td>
<td>something</td>
<td>{{ $price->discounted_price }}</td>
</tr>
#endforeach
#endforeach
#endforeach
Can anyone help me?

Cannot use object of type stdClass as array (View:

I want to use data 2 query in 1 view but
Error Cannot use object of type stdClass as array
(View:
public function adtranspc(Request $request)
{
$writter = Writter::all();
$processmaster = DB::table('rocessmaster')
->where('pcm_bname', 'LIKE', "%Social%")
->get();
return view('processspj.adtranspc',[
'writter' => $writter,
'processmaster' => $processmaster
]};
*This is my view (this error here)
<table id="table2" class="table table-hover table-striped">
<tr>
<th scope="col"></th>
<th scope="col">Colname1</th>
</tr>
#foreach ($processmaster as $item)
<tr>
<td>{{ $item['pcm_id'] }}</td>
<td>{{ $item['pcm_bname'] }}</td>
</tr>
#endforeach
</table>
This is my controller
public function adtranspc(Request $request)
{
$writter = Writter::all();
$processmaster = DB::table('rocessmaster')
->where('pcm_bname', 'LIKE', "%Social%")
->get();
return view('processspj.adtranspc',[
'writter' => $writter,
'processmaster' => $processmaster
]};
}
You are trying to print your object values as an array.You need to update your code with this, access your object values like this way
#foreach ($processmaster as $item)
<tr>
<td>{{ $item->pcm_id }}</td>
<td>{{ $item->pcm_bname }}</td>
</tr>
#endforeac

Print indexed array value in view.blade.php in laravel5.2

I have one associative array $collection and one indexed array $gnd which I have passed from Controller to my view.blade.php in Laravel 5.2. I want to print the values of both the arrays in a single table. Here is my code,
<table class="responsive-table highlight centered">
<thead>
<tr>
<th data-field="id">Sl.no</th>
<th data-field="name">Unique </th>
<th>Name</th>
<th data-field="price">Description</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
{{-- */$j = 1;/* --}}
#foreach($collection as $key=>$value)
<tr>
<td>{{ $j }}</td>
<td>{{ $value->uid }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->desc }}</td>
<td>{{ $gnd[$j] }}</td>
{{-- */$j++;/* --}}
#endforeach
</tr>
</tbody>
</table>
For {{ $gnd[$j] }} I am getting the following error.
ErrorException in b7c1ab515a44988c31e1982a3ce014434e97ef2c.php line 30:
Undefined offset: 22 (View: /var/www/html/anudip/resources/views/plugins/entries/view.blade.php)
I am new in laravel. Please help me...
Function that passes the two arrays from Controller:
public function getDetails(){
$collection = DB::table('entry_transactions')
->leftJoin('entry_masters', 'entry_transactions.entry_id', '=', 'entry_masters.id')
->get(['entry_masters.id as uid','entry_masters.name as name','entry_masters.gender as gender','entry_transactions.entry_desc as desc']);
$gnd = array();
$len = sizeof($gnd);
$i = 0;
foreach ($collection as $key) {
if($key->gender == 0){
$gnd[$i] = "Male";
}
else {
$gnd[$i] = "Female";
}
$i++;
}
return view($this->url.'entries.view', compact('collection','gnd'));
}
The error you are getting because both array's size are not equal!
And why are you starting $j = 1? shouldn't be $j = 0, if both your arrays has the same size $j = 0 will fix your problem and change <td>{{ $j }}</td> to <td>{{ $j+1 }}</td>
Also, can you show us your controller function that is sending this two arrays?

Resources