Sending variable through href - php

I am trying to pass a variable through an href url on my View, and have the Controller function query based on those variables. Here is code to get a better idea.
#foreach ($totalCount as $id => $name) {{-- id is the admin id --}}
<?php
$admin_id = $id;
?>
#foreach($name as $n => $status) {{-- $n is the name, $status is array of the counts --}}
<tr>
<td>
{{$n}}
<br>
Closed
</td>
<td>{{ isset($status[2]) ? $status[2] : 0 }}</td>
<td>{{ isset($status[1]) ? $status[1] : 0 }}</td>
<td>{{ isset($status[3]) ? $status[3] : 0 }}</td>
<td>{{ isset($status[4]) ? $status[4] : 0 }}</td>
<td>{{ isset($status[5]) ? $status[5] : 0 }}</td>
<td>{{ isset($status[6]) ? $status[6] : 0 }}</td>
</tr>
#endforeach
#endforeach
As you can see, I am getting that $id from my data structure and inputting it into $admin_id so I can use it. I take that admin id and place it into the href url so my controller can work with it and query properly.
Here is code from my controller:
public function index()
{
$query = AdvertiserApplication::with('admin');
$status = Input::get('status');
$id = Input::get('admin_id');
dd($id);
if(!empty($id)) {
$query->where('assigned_to', '=', $id);
}
if (!empty($status) || $status === '0')
$query->where('staus', '=', $status);
$applications = $query->get();
return View::make('admin.advertisers.application_list', ['applications' => $applications, 'admin_id' => AuthAdmin::admin(false)]);
}
What I am doing here is querying the whole table if $id and $status empty. (By the way status comes from a drop down table on the application list View.) The problem I am having is that the $id input is not working, it is coming in NULL. Any help would be appreciated!

Should be
Input::get('id');
Instead of
Input::get('admin_id');

You have to add $id as parameter of index function.
When variable is sent through href it is not element of GET/POST array.
So your function will lool like this:
public function index($id)
{
$query = AdvertiserApplication::with('admin');
$status = Input::get('status');
// $id = Input::get('admin_id');
// dd($id);
if(!empty($id)) {
$query->where('assigned_to', '=', $id);
}
if (!empty($status) || $status === '0')
$query->where('staus', '=', $status);
$applications = $query->get();
return View::make('admin.advertisers.application_list', ['applications' => $applications, 'admin_id' => AuthAdmin::admin(false)]);
}

Related

Undefined variable $result (View:/resources/views/frontend/CustomerRequest.blade.php)

when i run code then it gives this error: "Undefined variable $result (View:/resources/views/frontend/CustomerRequest.blade.php) ", anyone can plz suggest any solution. Thanks
controller:
public function index()
{
$result = DB:: select('select * from form_request');
$result= form::all();
return view('frontend.CustomerRequest')->with('result', $result);
}
view:
#foreach($result as $form)
<tr>
<td>{{ $form->id }}</td>
<td>{{ $form->name }}</td>
</tr>
#endforeach
route:
Route::get('customerrequest',[PostsController::class, 'index']);
Using the syntax return view('frontend.CustomerRequest')->with('result', $result); is wrong, that way does not pass the variable to the view page.
Instead it should be return view('frontend.CustomerRequest', compact('result');
So change your controller function to this
public function index()
{
$result = DB:: select('select * from form_request');
$result= form::all();
return view('frontend.CustomerRequest', compact('result');
}
Now in your view file you should be able to access the $result variable.

Laravel Excel::download returns blank file when records are too much

I have a functionality for downloading reports for orders in my DB based on a given period.
I am using "maatwebsite/excel": "^3.1".
Laravel version is 5.5.*
Here's some code:
Controller:
// ...Filtering orders from DB
Log::debug('Report baskets: '.$baskets->count());
return Excel::download(new ByStatusv2Export($baskets),
'finance_report_v2_' . now()->format('Y-m-d_U') . '.xlsx');
The ByStatusv2Export class:
class ByStatusv2Export extends DefaultValueBinder implements ShouldAutoSize, WithColumnFormatting, FromView, WithCustomValueBinder
{
protected $baskets;
public function __construct($baskets)
{
$this->baskets = $baskets;
}
public function view(): View
{
return view('warehouse::admin.export.financev2', ['baskets' => $this->baskets]);
}
public function columnFormats(): array
{
return [
'A' => NumberFormat::FORMAT_TEXT,
'B' => NumberFormat::FORMAT_TEXT,
'C' => NumberFormat::FORMAT_TEXT,
'D' => NumberFormat::FORMAT_TEXT,
'E' => NumberFormat::FORMAT_TEXT,
'J' => NumberFormat::FORMAT_TEXT,
];
}
public function bindValue(Cell $cell, $value)
{
if (Str::startsWith($cell->getCoordinate(), 'B')) {
$cell->setValueExplicit($value, DataType::TYPE_STRING);
return true;
}
if (Str::startsWith($cell->getCoordinate(), 'E')) {
$cell->setValueExplicit($value, DataType::TYPE_STRING);
return true;
}
if (Str::startsWith($cell->getCoordinate(), 'F')) {
$cell->setValueExplicit($value, DataType::TYPE_STRING);
return true;
}
if (Str::startsWith($cell->getCoordinate(), 'G')) {
$cell->setValueExplicit($value, DataType::TYPE_STRING);
return true;
}
if (Str::startsWith($cell->getCoordinate(), 'J')) {
$cell->setValueExplicit($value, DataType::TYPE_STRING);
return true;
}
// else return default behavior
return parent::bindValue($cell, $value);
}
}
I checked many checkpoints with dd($baskets) and it looks fine everywhere - The correct records are actually fetched from the database.
I have confirmed that the class receives the data and that the baskets property is set correctly.
Here is the financev2.blade.php:
<html>
<table>
<thead>
<tr>
<td>Статус</td>
<td>Продукт</td>
<td>Доставна цена</td>
<td>Продажна цена</td>
<td>IMEI</td>
<td>Дата на поръчка</td>
<td>Дата на завършване</td>
<td>Доставчик </td>
<td>Метод на плащане </td>
<td>Платено </td>
<td>Име на клиент </td>
<td>Фирма получател</td>
<td>Фирма</td>
<td>Номер на поръчка</td>
</tr>
</thead>
<tbody>
#foreach ($baskets as $basket)
#foreach ($basket->products as $product)
#foreach ($product->imei as $imei)
<tr>
<td>#lang('warehouse::admin.'.$basket->status)</td>
<td>{{ $product->product->title ?? '-' }}</td>
<td>{{ $imei->delivery_price }}</td>
<td>{{ !empty($imei->sale_price) ? $imei->sale_price : $product->getSellPrice($product->option_group_id) }}</td>
<td>{{ $imei->imei }}</td>
<td>{{ $basket->ordered_at->format('d-m-Y') }}</td>
<td>{{ $basket->finished_at->format('d-m-Y') }}</td>
<td>{{ !empty($basket->delivery_service) ? trans('warehouse::admin.'.$basket->delivery_service) : 'Rapido' }}</td>
<td>{{ trans('warehouse::admin.'.$basket->payment_method) }}</td>
#if($basket->isPaid())
<td>Да</td>
#else
<td>Не</td>
#endif
<td>{{ $basket->getContactName() }}</td>
<td>{{ $basket->getCompanyName() }}</td>
<td>{{ $basket->getSenderCompanyName() }}</td>
<td>{{ $basket->database_id }}</td>
</tr>
#endforeach
#endforeach
#endforeach
</tbody>
</table>
</html>
The problem is:
on the production server, when I select a larger period of time (let's say one month) it returns an empty excel sheet (this problem was not occuring before). With smaller periods (like 2-3 days sometime even a week it works).
On local with the same DB it works fine.
One thing I noticed is that when it fails it downloads the file very fast. Usually it takes some time process the data, but it seems like it gives up before even running through the foreachs in the blade file.
It does not record any errors in the logs.
I compared the php.ini configuration on both local and prod server and synced the values of params like memory_limit, max_execution_time etc. but still no effect.

Custom Calculation in Laravel Controller

I am new to Laravel. I'm building a small app which displays the user table from the DB, but before sending it to the view, I want to include a custom value from another function.
The accounts table fetches the list of accounts from MySQL, and I want to include a custom function called getStatus() which I get from an API.
Code
<?php
public function accounts()
{
$accounts = DB::table('accounts')
->where('profile_id', '=', Auth::id())
->get();
foreach ($accounts as $account) {
$account->status = getStatus($account->accno);
}
$data = compact('accounts');
return view::make('transactions', ['accounts' => $data]);
}
View
#foreach ($accounts as $account)
<tr>
<td></td>
<td>{{ $account->login }}</td>
<td>{{ $account->status }}</td>
</tr>
#endforeach
You can do it like this.
$accounts = $accounts->map(function($account){
$account->status = getStatus($account->accno)
});
Hope this will help you.
Thanks
$accounts = DB::table('accounts')
->where('profile_id', '=', Auth::id())
->get()
->map(function($item){
$item->status = getStatus($item->accno);
return $item;
});
Now you'll have status in your $accounts.

Laravel - pass ajax variables to model

In my User Model i have this getter method:
public function getWorkedHoursInRangeAttribute($start, $end)
{
$sum = [];
foreach($this->workedTimes as $item) {
if( ($item->start_time->gt($start)) && ($item->end_time->lt($end)) ){
array_push($sum, ceil($item->end_time->diffInMinutes($item->start_time->addMinutes($item->break_time_min))/60 * 4) / 4 );
}
}
return array_sum($sum);
}
And in my view i post this
function(start, end) {
$.ajax({
type: "POST",
url: '/users/workedhours',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: {"start": start.format("DD.MM.YYYY HH:mm"), "end": end.format("DD.MM.YYYY HH:mm")},
and i have this in my Controller
public function getWorkedHoursForRange(Request $request)
{
$start = Carbon::parse($request->start);
$end = Carbon::parse($request->end);
return response()->json(['msg' => $start], 200);
}
and this route:
Route::post('users/workedhours', 'UsersController#getWorkedHoursForRange');
How can i take this start and end variables from ajax to my Model method and make calculation?
I will probably need to do something in my Controller...but what?
UPDATE:
in view i have this foreach loop for my table:
<tbody>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->total_time_current_year }}</td>
<td>{{ $user->total_time_last_year }}</td>
<td>{{ $user->total_time_current_month }}</td>
<td>{{ $user->total_time_last_month }}</td>
<td>here i need the calculation for date range</td>
</tr>
#endforeach
</tbody>
You need two attributes in your model: start and end. That way you are able to access them in your accessor.
protected $start;
protected $end;
public function getWorkedHoursInRangeAttribute()
{
$sum = [];
foreach($this->workedTimes as $item) {
if( ($item->start_time->gt($this->start)) && ($item->end_time->lt($this->end)) ){
array_push($sum, ceil($item->end_time->diffInMinutes($item->start_time->addMinutes($item->break_time_min))/60 * 4) / 4 );
}
}
return array_sum($sum);
}
You than make your AJAX call to the controller, loop through the users, set start and end vars to each user-model and return all users to the view. There you can access your accessor-attribute.
public function getWorkedHoursForRange(Request $request)
{
$start = Carbon::parse($request->start);
$end = Carbon::parse($request->end);
$users = App\User::all();
foreach($users as $user) {
$user->start = $start;
$user->end = $end;
}
return response()->json(['users' => $users], 200);
}

updateExistingPivot won't work

I'm trying to update my pivot table approve_document where it has a extra column isApprove using ->withPivot method.
Model:
Document
class Document extends Model
{
public function sentToApprovers()
{
return $this->belongsToMany('App\Models\Approve', 'approve_document')->withPivot('isApprove');
}
}
Approve
class Approve extends Model
{
public function createdpendingDocuments()
{
return $this->belongsToMany('App\Models\Document', 'approve_document')->withPivot('isApprove');
}
}
This is where I get all my records in my approve_document.
Controller:
public function documentsSentForApproval()
{
$pendingDocumentLists = DB::table('approve_document')
->select('documents.title', 'documents.content', 'categories.category_type', 'users.username', 'approve_document.dateReceived', 'documents.id', 'approves.approver_id')
->join('documents', 'documents.id', '=', 'approve_document.document_id')
->join('categories', 'categories.id', '=', 'documents.category_id')
->join('approves', 'approves.id', '=', 'approve_document.approve_id')
->join('users', 'users.id', '=', 'approves.approver_id')
->where('approver_id', '=', Auth::id())
->orWhere('requestedBy', '=', Auth::id())
->get();
return view ('document.pending')
->with('pendingDocumentLists', $pendingDocumentLists);
}
View:
#foreach ($pendingDocumentLists as $list)
<tr class = "info">
<td>{{ $list->title }}</td>
<td>{{ strip_tags(substr($list->content, 0, 50)) }} {{ strlen($list->content) > 50 ? "..." : '' }}</td>
<td>{{ $list->category_type }}</td>
<td>{{ $list->username }}</td>
<td>{{ date('M, j, Y', strtotime($list->dateReceived)) }}</td>
<td>
#if (Auth::id() == $list->approver_id)
<a href = "{{ route ('document.pending', $list->id) }}">
<button type = "submit" class = "btn btn-success glyphicon glyphicon-thumbs-up"> Approve</button>
</a>
#endif
</td>
<td></td>
</tr>
#endforeach
You can see here I have a approve button where I need to set isApprove to true when the button is clicked. You can see that I get the current id of the document when the button was clicked.
This part of the Controller where I'm having a hard time updating my pivot table. It gives me a error MethodNotAllowedHttpException. Any tips or help would greatly appreciated!
public function updateIsApprove($id)
{
$document = new Document();
foreach ($document as $update)
{
$approve = new Approve();
$document->sentToApprovers()->updateExistingPivot([$approve->id => ['isApprove' => '1']],false);
}
return redirect()->route('document.pending');
}
routes:
Route::post('/documents/pending/approve/{id}',
[
'uses' => '\App\Http\Controllers\DocumentController#updateIsApprove',
'as' => 'document.pending',
]);
public function updateExistingPivot($id, array $attributes, $touch = true)
First parametr should be id of related thing.
public function updateIsApprove($documentId, $approveId)
{
$document = Document::find($documentId);
if (!$document) {
// Handle error that document not exists.
}
$approve = $document->sentToApprovers()->find($approveId);
if (!$approve) {
// Handle that approve not exists or is not related with document.
}
$document->sentToApproves()->updateExistingPivot($approve->id, ['isApprove' => 1]);
return redirect()->route('document.pending');
}
MethodNotAllowedHttpException is not for your controller but is for your Route. As you can see, in your Routes file, you have Route for handling POST request, but in your view you are making a GET request by accessing the URL directly.
So, just change the POST route to GET in your Routes file.
Route::get('/documents/pending/approve/{id}',
[
'uses' => '\App\Http\Controllers\DocumentController#updateIsApprove',
'as' => 'document.pending',
]);

Categories