Laravel 8 - one to many relationship total count not working - php

I have a Truck and Package table with One to Many relationships.
One truck has many packages and one package belongs to one truck.
I have a no_of_items column to display the total number of packages that belong to a particular truck. This is how I define it inside Truck Controller:
public function store(Request $request)
{
$request->validate([
'truck_number'=>'required|unique:trucks',
'no_of_items',
'postman_name'=>'required',
'date_of_operation'=>'required',
'status'=>'required'
]);
$trucks = new Truck([
'truck_number' => $request->get('truck_number'),
'no_of_items' => $request->get('no_of_items'),
'postman_name' => $request->get('postman_name'),
'date_of_operation' => $request->get('date_of_operation'),
'status' => $request->get('status')
]);
$trucks->save();
return redirect(TRUCK)->with('success', 'Truck Details Saved!');
}
But it doesn't display anything on the truck/index.blade.php or anywhere else. Why is that?
My Models:
class Truck extends Model
{
use HasFactory;
protected $primaryKey = 'truck_id';
protected $fillable = ['truck_number', 'no_of_items', 'postman_name', 'date_of_operation', 'status'];
public function Package()
{
return $this->hasMany(Package::class, 'truck_number');
}
}
class Package extends Model
{
use HasFactory;
protected $primaryKey = 'package_id';
protected $fillable = ['truck_number', 'package_number', 'destination', 'date_of_operation'];
public function Truck(){
return $this->belongsTo(Truck::class);
}
}
truck/index.blade.php file:
<table class="table table-striped mt-5">
<thead>
<tr>
<th>No</th>
<th>Truck Number</th>
<th>Quantity</th>
<th>Postman in Charge</th>
<th>Operation Date</th>
<th>Status</th>
<th colspan="2" class="text-center">Actions</th>
</tr>
</thead>
<tbody>
#foreach($trucks as $count => $truck)
<tr>
<td>{{++$count}}</td>
<td>{{$truck->truck_number}}</td>
<td>{{$truck->Package()->count()}}</td>
<td>{{$truck->postman_name}}</td>
<td>{{$truck->date_of_operation}}</td>
<td>{{$truck->status}}</td>
<td class="text-center">
Edit
</td>
<td class="text-center">
<form action="{{ route('truck.destroy', $truck->truck_id)}}" method="post">
#csrf
#method('DELETE')
<button class="btn btn-danger btn-block" type="submit">Delete</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="text-center">
<a style="margin: 19px;" href="{{ route('truck.create')}}" class="btn btn-primary bg-success">New Truck Details</a>
</div>

Modify your relationship this way because by default the laravel will refer to the primary id of the model which did not match on your relationship foreign keys
public function Package()
{
return $this->hasMany(Package::class, 'truck_number','truck_number');
}

Related

How do i calculate and view total work_time for specific id in laravel?

I have two tables employes and attendances . What I want is to sum work_time for each employe id and show in my view.
employes Table
id
attendances Table
id
employe_id
work_time
I want to sum work_time column for specific employe id. I am new to laravel so how do I do that with laravel eloquent.
Employe.php
class Employe extends Model{
use HasFactory;
protected $fillable=['id','employe_code','employe_name','workplace'];
public function employee(){return $this->hasMany(Attendance::class);}}
Attendance.php
class Attendance extends Model{use HasFactory;
protected$fillable['id','employe_id','attendence_date','clock_in','clock_out','work_time','attendence_status'];
public function employe()
{return $this->belongsTo('App\Models\employe', 'employe_id');}}
AttendanceController
public function attendance(){
$attendances = Employe::all();
$hour = Attendance::where('employe_id',1)->sum('work_time');
return view('pages.Attendance.hour', compact('attendances','hour')); }
hour.blade.php
```
<table id="datatable" class="table table-hover table-sm table-bordered p-0" data-page-length="50"
style="text-align: center">
<thead>
<tr>
<th class="alert-success">#</th>
<th class="alert-success">employe_code</th>
<th class="alert-success">employe_name</th>
<th class="alert-success">work_time</th>
</thead>
<tbody>
#foreach($attendances as $attendances)
<tr>
<td></td>
<td>{{ $attendances->employe_code }}</td>
<td>{{ $attendances->employe_name }}</td>
<td>Hour {{ $hour }} </td>
</tr>
#endforeach
</table>
Only for Laravel 8.12 and above, you can use withSum()
First of all, correct the relation name in Employe.php
class Employe extends Model{
use HasFactory;
protected $fillable=['id','employe_code','employe_name','workplace'];
public function attendances(){ //<---- here
return $this->hasMany(Attendance::class);
}
}
Here is the controller
public function attendance(){
$attendances = Employe::query()->withSum('attendances', 'work_time')->get();
return view('pages.Attendance.hour', compact('attendances'));
}
And the blade (kept the variable name $attendances but you should change it to employees)
<table id="datatable" class="table table-hover table-sm table-bordered p-0" data-page-length="50" style="text-align: center">
<thead>
<tr>
<th class="alert-success">#</th>
<th class="alert-success">employe_code</th>
<th class="alert-success">employe_name</th>
<th class="alert-success">work_time</th>
</thead>
<tbody>
#foreach($attendances as $employe)
<tr>
<td></td>
<td>{{ $employe->employe_code }}</td>
<td>{{ $employe->employe_name }}</td>
<td>Hour {{ $employe->attendances_sum_work_time }} </td>
</tr>
#endforeach
</table>

How to get the name of user through relations in Laravel

I want to implement simple teaming option to my app. I have theese tables:
users/teams /team_members/
-----/---------/------------/
id /id /id /
name /user_id /user_id /
... /... /team_id /
I have 3 models where I have defined relations:
User model:
public function teams() {
return $this->hasOne(Team::class);
}
public function teamMembers() {
return $this->hasManyThrough(Team::class, TeamMembers::class);
}
Team model:
public function user() {
return $this->belongsTo(User::class);
}
public function members() {
return $this->hasMany(TeamMember::class);
}
TeamMember model:
public function user() {
return $this->belongsTo(User::class);
}
User can only create one team, but join many teams. The problem I have is with displaying data in the frontend.
This is the query I make in the controller:
public function index(User $user) {
$teams = Team::where('user_id', auth()->user()->id )->with('members')->get();
return view('teams.index')->with('teams', $teams);
}
I have a table with the members of the current autheticated user team. I want to display the names if each member but the only thing i can do is $team->member->id and I get the ids of the users but I want to get their names too. I can do it with simple query but I dont want to make new query for every row.
This is the blade file:
#if ( $teams->count() > 0 )
#foreach ($teams as $team)
<table class="table table-striped table-sm table-responsive-lg">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Members</th>
<th scope="col">Created</th>
<th scope="col" colspan="2"></th>
</tr>
</thead>
<tbody>
<tr>
<td>{{$team->name}}</td>
<td>{{ $team->members->count('members')}} {{ Str::plural('member', $team->id) }}</td>
<td>{{ $team->created_at->diffForHumans() }}</td>
<td>
Edit
</td>
<td>
<form action="" method="POST">
#method('DELETE')
#csrf
<button class="btn btn-sm btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
</tbody>
</table>
<br>
<h5>Team members:</h5>
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Added</th>
</tr>
</thead>
<tbody>
#foreach ($team->members as $member)
<tr>
<td>{{ $member->user->name }}</td>
<td>{{ $member->created_at->diffForHumans() }}</td>
</tr>
#endforeach
</tbody>
</table>
#endforeach
#else
<div class="container">
<h2>You do not own a team</h2>
<p class="lead text-muted">You can create your own team or join the team of other user.</p>
<p>
Create team
Join team
</p>
</div>
#endif
When I changed $team->member->id with $member->user->name it worked. It shows the names of the users but I get N+1 queries alert and I don't know how to fix it (i tried different queries and relations but it didnt work):
You are accessing the user relationship from each member. So lets eager load that relationship as well.
public function index(User $user)
{
$teams = Team::where('user_id', auth()->user()->id )->with('members.user')->get();
return view('teams.index')->with('teams', $teams);
}

Search results shows everything in database and show image in results

I have a search function in my laravel project, when I navigate to the search page it shows all the entries in the database. I would like it to show nothing until I put something in the search field. Furthermore, when the results are displayed I would like an image to be dispalyed.
Here are the relavent files:
public function search(Request $request){
$query = $request->input('query');
$result = Photo::search($query)->get();
return view('search.results')->with('result', $result);
}
Here is the model
class Photo extends Model
{
use SearchableTrait;
protected $searchable = [
'columns' => [
'photos.title' => 10,
'photos.description' => 10,
'photos.photo' => 10,
],
];
protected $fillable = array('photo','title','description','album_id');
public function album(){
return $this->belongsTo('App\Album');
}
}
The display.blade.php
<div class="row">
<div class="col-8">
<table class="table table-bordered table-stripped">
<thead>
<tr>
<th>Image</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
#foreach($result as $res)
<tr>
<th><img src="/storage/photos/."{{$album_id}}/{{$res->photo}}</a></th>
<th>{{$res->title}}</th>
<th>{{$res->description}}</th>
</tr>
#endforeach
</tbody>
</table>
In the above code I get an error message about not being able to find $album_id.
As always thank you for your help

Laravel - How to Implement Search from Controller and View

I am using Laravel-5.8 for web application. I have this model class:
class HrEmployee extends Model
{
protected $table = 'hr_employees';
protected $fillable = [
'employee_code',
'address',
'company_id',
'email',
'employment_date',
'first_name',
'last_name',
'local_government_id',
'nationality_id',
'other_name',
'password',
'phone',
'resignation_date',
'is_hod',
'department_id',
];
protected $dates = [
'created_at',
'updated_at',
'date_of_birth',
'employment_date',
'resignation_date',
];
public function company()
{
return $this->belongsTo('App\Models\Organization\OrgCompany','company_id');
}
public function department()
{
return $this->belongsTo('App\Models\Organization\OrgDepartment','department_id');
}
public function fullName()
{
return $this->first_name . ' ' . $this->other_name . ' ' . $this->last_name;
}
}
Controller
class HrEmployeesController extends Controller
{
public function index()
{
$userCompany = Auth::user()->company_id;
if (Auth::user()->hasRole('Super Admin')) {
$employees = HrEmployee::paginate(6);
} else {
$employees = HrEmployee::where('company_id', $userCompany)->paginate(6);
}
return view('hr.employees.index')->with('employees', $employees);
}
}
view
<table class=" table table-bordered table-striped table-hover datatable">
<thead>
<tr>
<th width="10">
#
</th>
<th>Name</th>
<th>Email</th>
<th>Employee Code </th>
<th>Designation</th>
<th>Department</th>
<th>Employment Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach($employees as $key => $employee)
<td>
{{$key+1}}
</td>
<td>
{{$employee->first_name}} {{$employee->last_name}}
</td>
<td>
{{$employee->email}}
</td>
<td>
{{isset($employee->employee_code) ? $employee->employee_code : ''}}
</td>
<td>
{{isset($employee->designation) ? $employee->designation->designation_name : ''}}
</td>
<td>
{{isset($employee->department) ? $employee->department->dept_name : ''}}
</td>
<td>
{{$employee->employment_date ? Carbon\Carbon::parse($employee->employment_date)->format('d-m-Y') : 'N/A' }}
</tr>
#endforeach
</tbody>
</table>
I want the users to be able to search by Name (first_name and last_name) - textbox, department - dropdownlist and employee_code - textbox. When the user is done, he clicks on submit button, then the result is displayed.
How do I implement this from both controller and view.
Thank you.
you can add $request var or just use $_GET on index function to get param/query of search and use where "LIKE" to filter your data
make form in your view
<form action="">
<div class="input-group col-md-4">
<input type="text" name="s" class="form-control" value="{{ $_GET['s'] ?? '' }}" placeholder="Search something...">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Search!</button>
</span>
</div>
</form>
and your controller on index function
$s = ($_GET['s']??'');
$employees = HrEmployee::where(function($q){
$q->where('first_name','LIKE','%'.$s.'%')->orWhere('last_name','LIKE','%'.$s.'%');
})->paginate(10)->appends($_GET);
I try to give you code that i always do,
in your blade add this code
{{ Form::open(['action'=> 'HrEmployeesController#search', 'method'=>'POST']) }}
<label>Barcode : {{Form::text('FirstName','',['class'=>'form-control', ])}} </label>
{{Form::submit('Submit',['class'=>'btn btn-primary btn-sm button'])}}
{{Form::close()}}
while in your controller add search fuction
public function search(Request $request)
{
//
$employees = HrEmployee::where('first_name','like',"%".$request->input('FirstName')."%")->paginate(6)
return view('hr.employees.index')->with('employees', $employees);
}
and add it to your web.php
Route::post('employees/Search','HrEmployeesController#search');
You can understand the idea i give and hope it help

How can I rearrange this table to another away laravel eloquent relation

I used laravel hasmany relationship in my user model. I just want to convert my table like below (row to column):
To:
Here is my User model:
public function meal(){
return $this->hasMany(Meal::class);
}
My controller:
public function index()
{
$members = User::all();
return view('admin.meal')->with([
'members' => $members,
]);
}
and #blade
<table class="table table-striped #if(count($members)>7) table-responsive #endif ">
<thead>
<tr class="text-uppercase">
{{--<th class="font-w700">Date</th>--}}
#foreach($members as $member)
<th class="font-w700">{{str_limit($member->fname,5,'...')}}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach($members as $member)
<tr>
#foreach($member->meal as $meal)
<td><span class="font-w600">{{$meal->user_id}}</span></td>
#endforeach
</tr>
#endforeach
</tbody>
</table>

Categories