Laravel eloquent realationships - php

This is my problem.
I have a model called Product that defines a relation like this
Product.php
public function maintenanceById($maintenanceId){
return $this->belongsToMany(Maintenance::class, 'product_maintenance')->where('maintenance_id', '=', $maintenanceId)->withPivot(['price', 'code']);
}
I use this method in a view like so
#foreach($maintenance as $value)
#if($product->maintenanceById($value->id)->getResults())
<th>
{{$product->maintenanceById($value->id)->getResults()[0]->pivot->price}}
</th>
#else
<th></th>
#endif
#endforeach
getResults returns an array that has a single object in it so I have to access the object within using getResults()[0]. Is there a way to make the returned value into an object so I can simply do this:
$product->maintenanceById($value->id)->getResults()->pivot->price
EDIT:
Ive tried this and it works
public function maintenanceById($maintenanceId){
return $this->belongsToMany(Maintenance::class, 'product_maintenance')->where('maintenance_id', '=', $maintenanceId)->withPivot(['price', 'code'])->get();
}
Then in the view
#foreach($maintenance as $value)
#if(!$product->maintenanceById($value->id)->isEmpty())
<th>£ {{$product->maintenanceById($value->id)->first()->pivot->price}}</th>
#else
<th></th>
#endif
#endforeach
But when I try the following code it doesn't work.
public function maintenanceById($maintenanceId){
return $this->belongsToMany(Maintenance::class, 'product_maintenance')->where('maintenance_id', '=', $maintenanceId)->withPivot(['price', 'code'])->first();
}
#foreach($maintenance as $value)
#if(!$product->maintenanceById($value->id)->isEmpty())
<th>£ {{$product->maintenanceById($value->id)->pivot->price}}</th>
#else
<th></th>
#endif
#endforeach

Related

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

Destroy() in Basic Controller is not working

So I'm printing user complaints in table where I'm also printing a Delete button with every row. When I click that delete button, I want to delete that specific complaint from the table. I'm not using Resource Controller for this but a Basic Controller. Now, this is my code:
ViewComplaint.blade.php (Complaints Table with Delete Button):
<table id="cTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>Student Name</th>
<th>Complaint Title</th>
<th>Complaint Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($complaints as $complaint)
<tr>
<td>{{ $complaint->name }}</td>
<td>{{ $complaint->cname }}</td>
<td>{{ $complaint->cbody }}</td>
<td class="btn-group">
{!! Form::open(array('route'=>['complaint.destroy',$complaint->id],'method'=>'DELETE')) !!}
{!! Form::submit('Delete',['type'=>'submit','style'=>'border-radius: 0px;','class'=>'btn btn-danger btn-sm',$complaint->id]) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
</tbody>
</table>
Web.php (Routes):
Route::get('/complaint/create','ComplaintController#create')->name('complaint.create');
Route::post('/complaint','ComplaintController#store')->name('complaint.store');
Route::get('/complaint','ComplaintController#index')->name('complaint.index');
Route::delete('/complaint/{$complaint->id}','ComplaintController#destroy')->name('complaint.destroy');
ComplaintController.php (Basic Controller):
class ComplaintController extends Controller
{
public function index() {
$complaints = Complaint::all();
return view('viewcomplaint',compact('complaints'));
}
public function create(User $user) {
$user = User::all();
$user->name = Auth::user()->name;
return view('createcomplaint',compact('user'));
}
public function store(Request $request, Complaint $complaint, User $user) {
$user = User::find($user);
$complaint->name = Auth::user()->name;
$complaint->cname = $request->input('cname');
$complaint->cbody = $request->input('cbody');
//update whichever fields you need to be updated
$complaint->save();
return redirect()->route('home.index');
}
public function destroy(Complaint $complaint,$id)
{
$complaint = Complaint::findOrFail($complaint->id);
$complaint->delete();
return redirect()->route('complaint.index');
}
}
Now when I click the Delete button on the table, it just gives me "404 | Not Found" error. What am I doing wrong here? I would really appreciate some help.
remove the $id from the route
Route::delete('/complain/{id}','ComplaintController#destroy')->name('complaint.destroy');
public function destroy($id) {
}
The route parameter is just a name; you are saying this particular route segment is dynamic and I want the parameter named complaint:
Route::delete('complaint/{complaint}', 'ComplaintController#destroy')->name('complaint.destroy');
Then you can adjust your destroy method to take the parameter complaint typehinted as Complaint $complaint to get the implicit binding:
public function destroy(Complaint $complaint)
{
$complaint->delete();
return redirect()->route('complaint.index');
}
Seems to me you're defining your route wrong. Change your route to:
Route::delete('/complaint/{id}','ComplaintController#destroy')->name('complaint.destroy');
You don't need an array() in your form opening, so hange your form opening to this:
{!! Form::open(['method' => 'DELETE', 'route' => ['complaint.destroy',$complaint->id]]) !!}
And remove the $complaint->id from your submit button, you don't need it there.
All you have to do now inside your function is to find Complaint that has the id you passed in your form:
public function destroy($id)
{
$complaint = Complaint::findOrFail($id);
$complaint->delete();
return redirect()->route('complaint.index');
}
Let me know if you stumble on any errors.

How to fix Show category in laravel

Hi I'm building a ticket system i made tables with heads as:
<table class="table">
<thead>
<tr>
<th>Category</th>
<th>Title</th>
<th>Status</th>
<th>Last Updated</th>
</tr>
</thead>
I'm having trouble calling category name in views:
#foreach ($tickets as $ticket)
#foreach ($categories as $category)
#if ($category->id === $ticket->category_id)
{{ $category->name }}
#endif
#endforeach
My #if statements seems to be wrong i thinks as i can pull all the category names but with #if code seems to be breaking and its showing me nothing.
My routes:
Route::get('my_tickets', 'TicketsController#userTickets');
My Controller Function:
public function userTickets()
{
$tickets = Ticket::where('user_id', Auth::user()->id)->paginate(10);
$categories = Category::all();
return view('tickets.user_tickets', compact('tickets', 'categories'));
}
Update:
My Category Model:
protected $fillable = ['name'];
public function tickets()
{
return $this->hasMany(Ticket::class);
}
&Ticket Model:
protected $fillable = [
'user_id', 'category_id', 'ticket_id', 'title', 'priority', 'message', 'status'
];
public function category()
{
return $this->belongsTo(Category::class);
}
I'm trying to follow this tutorial but i think I'm doing something wrong idk what.
https://scotch.io/tutorials/build-a-support-ticket-application-with-laravel-part-1
https://scotch.io/tutorials/build-a-support-ticket-application-with-laravel-part-2
I think that you are trying to do something like this:
#foreach ($tickets as $ticket)
{{ $ticket->category->name }}
#endforeach
If you made a relation between your classes with belongsTo and hasMany then you can access using $ticket->category->name. If it does not work perhaps you have to get tickets with:
$tickets = Ticket::with('category')->where('user_id', Auth::user()->id)->paginate(10);
You haven't really followed it through. See how it's done in the article
#foreach ($tickets as $ticket)
#foreach ($categories as $category)
#if ($category->id === $ticket->category_id)
{{ $category->name }}
#endif
#endforeach
$ticket->$category is not a valid syntax.

Laravel 5.2 correct way to use variables in blade

So I know about passing variables via the controller for instance if its a query array I will do
public function index()
{
$query = Request::get('q');
if ($query) {
$users = User::where('username', 'LIKE', "%$query%")->get();
}
return view('view', compact('users'));
}
And when on the blade I will do
#if( ! empty($users))
#foreach($users as $user)
{{ $user->username }}
#endforeach
#endif
Now my question is how do I set a variable using a variable from the foreach? at the moment I am using PHP inside of the blade template file but I feel this is messy, here is what I have
#if( ! empty($users))
#foreach($users as $user)
<?php
$lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($user->last_online))->diffForHumans();
$fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
?>
{{ $user->username }}
#if ($user->last_online <= $fiveMinsAgo)
{{ $lastOnline }}
#else
Online Now
#endif
#endforeach
#endif
found a solution to my issue if anyone else is ever looking for it.
public function getLastOnlineAttribute($value)
{
$fiveMinsAgo = \Carbon\Carbon::now()->subMinute(5);
$thirtMinsAgo = \Carbon\Carbon::now()->subMinute(30);
$lastOnline = \Carbon\Carbon::createFromTimeStamp(strtotime($value))->diffForHumans();
if ($value <= $fiveMinsAgo) {
echo 'Last Active: '.$lastOnline.'';
}
else {
echo 'Online Now';
}
}
Basically add this into your model for the variable (eg, if its a $user->last_online it would go into the user model) , it is called a eloquent mutator if you are ever looking for more info, https://laravel.com/docs/master/eloquent-mutators
It grabs your data for the variable for instance {{ $user->last_online }}
Note that the Underscore is transformed into a CamelCase in the function name, the output is set at $value, you can then set variables inside of the function and mould the output however you wish, then in the blade you can get rid of all the extra crap and just use {{ $user->last_online }}

laravel pagination : Call to a member function render() on array

In laravel controller I have following code:
public function getAdmins(){
//$users = $this->user->all();
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
$exceptSuperadmin = array();
foreach($users as $user){
if(!$user->isUser())
$staffs[] = $user;
}
$users = #$staffs;
return view('users::admins.list')->with('staffs',$users)->with('search',$search);
}
In Model I have:
public function findUsers($search)
{
return self::where('name','like','%'.$search['name'].'%')
->where('username','like','%'.$search['uname'].'%')
->where('role','like','%'.$search['role'].'%')
->paginate(5);
}
And In blade file I have:
#if($staffs)
#foreach($staffs as $staff)
<!-- Some code here to loop array -->
#endforeach
#else
No Staffs
#endif
{!! $staffs->render() !!} Error comes at this line
I am not geeting why this error comes....staffs is an array and render() a function to echo the pagination pages...but can't getting the error...Anybody to help.
By applying foreach the pager object and assign an array you lose the paging properties, so you will have an array rather than a pager object.
I recommend the following solution for your case:
Controller:
public function getAdmins(){
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
return view('users::admins.list')->with('users',$users)->with('search',$search);
}
Blade file:
#if($users)
#foreach($users as $user)
#if(!$user->isUser())
<!-- Some code here to loop array -->
#endif
#endforeach
#else
No Staffs
#endif
{!! $users->render() !!}
NO, render() doesn't work on an object per se, neither on the array you are creating out of the required object for the pagination to work (LengthAwarePaginator)
Since you have a collection, and you need one, you could use one of the methods provided to do your filtering, such as filter.
Something like (untested but should work):
$staff = $users->filter(function ($value, $key) {
return !$value->isUser();
});

Categories