Custom Calculation in Laravel Controller - php

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.

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.

Sending data from Controller to View in Laravel 7

I want to send my data from controller to xedit.blade.php, but I get the same error:
Undefined variable: users
in controller:
public function index3()
{
$users=User::all();
return view('xedit')->with('users' => $users);
}
Routes:
Route::get('/index3','Admin\UsersController#index3');
and I want to use $users in blade.Maybe there is a Route problem?
in your index method
public funtion index()
{
$users=User::all();
return view('xedit', compact('users'));
}
in your view add $users
<table>
#foreach ($users as $item)
<tr>
<td>{{ $item->id }}</td>
<td>{{ $item->name }}</td>
</tr>
#endforeach
</table>
Your code logic is perfect, I guess you have to use proper naming with your routes because of Laravel Standard.
Route::get('/admin/show','Admin\UsersController#index')-name('admin.show');
public function index()
{
$users = User::all();
return view('xedit')->with('users' => $users);
}
In view, blade use a professional approach like below
#isset($users)
... loop ...
#endisset()
check record before sending to view by using dump and die function dd($users);
Want to comment but doesn't have 50 reputation
Replace ('users' => $users); this with (['users' => $users]); as you are using =>

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',
]);

Sending variable through href

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

Laravel 5 check if pivot data is already in database

Got a ManyOnMany system (3 tables, projects, users, project_user)
Many users can work on a project, and a user can have many projects.
When checkbox = checked it sends the database to the pivot table.
Now I'm facing the problem that everytime I click the project/user id will get send to the project_user table.
And I need to have the checkbox already checked when the user is actually added to the project.
So how I see it: the form::checkbox has a third function checked or not checked, and with an if/else statement in my controller.edit I will have a validation somehow. Please help me!
Blade:
#foreach($users as $user)
<tr>
<td>
{{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
</td>
<td>
{!! Form::checkbox('contribute['.$user->id.']', '1', $checkifinproject) !!}
</td>
</tr>
#endforeach
Controller:
public function edit($id, Project $project)
{
$users = User::all();
$project = $this->project->find($id);
if ($users == $project)
{
$checkifinproject = 'checked';
}
else {
}
return view('project.edit', ['project' => $project, 'id' => 'edit', 'project_id' => $id], compact('users'));
}
public function update(CreateProjectRequest $request)
{
if($request->get('contribute'))
{
foreach($request->get('contribute') as $k => $contribute)
{
if($contribute == 1)
{
$project = $this->project->find($request->project_id);
$project->users()->attach($k);
}
}
}
$project = $this->project->find($request->project_id);
$project->fill($request->input())->save();
return redirect('project');
}
Model:
User
public function projects()
{
return $this->belongsToMany('App\Project', 'project_user', 'user_id', 'project_id');
}
Project
public function users()
{
return $this->belongsToMany('App\User', 'project_user', 'project_id', 'user_id');
}
I think the issue is you are comparing two things that will never be the same and trying to determine if that user belongs to the project. A better thing to do would be to query all the users with their projects and as you loop through the users, check to see that the project you are modifying is one of the projects the user belongs to.
That can be done like this...
Controller
public function edit($id, Project $project)
{
$users = User::with('projects')->get();
$project = $this->project->find($id);
return view('projects.edit', ['users' => $users, 'project' => $project]);
}
View
#foreach($users as $user)
<tr>
<td>
{{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
</td>
<td>
{!! Form::checkbox('contribute['.$user->id.']', '1', $user->projects->contains('id', $project->id)) !!}
</td>
</tr>
#endforeach

Categories