Laravel - How to Implement Search from Controller and View - php

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

Related

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

Laravel 8 - one to many relationship total count not working

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

how to store n number of employee attendance data a ta time with their id in another table as any other column name

Model 1
namespace App;
use Illuminate\Database\Eloquent\Model;
class employee_attendence extends Model
{
//
protected $fillable = array('is_present' ,'date' );
//protected $fillable=[];
public $timemstamps= false ;
public function employee_data(){
//return $this->hasOne(employee_data::class,'App/employee_data');
return $this->hasOne('App\employee_data');
}
}
model 2
namespace App;
use Illuminate\Database\Eloquent\Model;
class employee_data extends Model
{
//protected $fillabel=['first_name','last_name','contact_no','date_joining','post'];
protected $fillable = array('first_name', 'last_name', 'contact_no' ,'date_joining','post' );
//protected $fillable=[];
public $timemstamps= false ;
public function employee_attendence()
{
//return $this->hasOne( employee_attendence::class, 'App/employee_attendence');
return $this->belongsTo('App\employee_attendence');
}
}
controller
public function Attendence()
{
$data=employee_data::all();
return view('attendence',compact('data'));
}
public function mark_attendence(Request $request)
{
$request->validate([
'date' => 'required',
'is_present' => 'required'
]);
$employee = new employee_attendence([
'is_present' => $request->get('is_present'),
'date' => $request->get('date')
]);
$employee->save();
$employee->employee_data()->create([]);
return redirect('/index')->with('succ','Attendence Added Successfully');
}
form
<table class="table table-bordered ">
<tr>
<th width="5%">Id</th>
<th width="15%">First Name</th>
<th width="15%">Last Name</th>
<th width="15%">DateOfJoining</th>
<th width="10%">post</th>
<th width="15%">Date</th>
<th width="10%">Remark</th>
<th width="30%">Action</th>
</tr>
#foreach( $data as $row )
<tr>
<td>{{ $row->id }}</td>
<td>{{ $row->first_name }}</td>
<td>{{ $row->last_name }}</td>
<td>{{ $row->date_joining }}</td>
<td>{{ $row->post }}</td>
<td><input type="date" value="CURDATE()" name="date" ></td>
<td>
<label class="form-check-label" for="radio2">
<input type="checkbox" class="form-check-input" id="Present" name="is_present" value="Present">&nbsp &nbsp Present
</label><br>
<label class="form-check-label" for="radio2">
<input type="checkbox" class="form-check-input" id="Absent" name="is_present" value="Absent">&nbsp &nbsp Absent
</label></td>
<td>
<button type="Submit" class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span></button>
</td>
</tr>
#endforeach
store id from table 1 as user_id in table2

Property missing in laravel

I have setup my localhost to new PC. After import the database to phpmyadmin, I run laravel and open the page. However, I got this error:
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\inventoryApp\resources\views\Item\edit.blade.php)
On the other page, I got this error:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\inventoryApp\resources\views\Item\show.blade.php)
My view code looks like:
<table id="sale-table" class="table table-bordered table-striped table-hover datatable">
<thead>
<tr>
<th>No</th>
<th>Seller</th>
<th>Item ID</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Total Sale</th>
<th>Detail</th>
<th>Action</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($sales as $sale)
<tr>
<td>{{ $sale->id }}</td>
<td>{{ $sale->user->name }}</td>
<td>{{ $sale->item_id }}</td>
<td>{{ $sale->item->name }}</td>
<td>{{ $sale->quantity }}</td>
<td>RM {{ $sale->price }}</td>
<td>{{ $sale->created_at }}</td>
#if(Auth::user()->type=='admin'||Auth::user()->type=='super_admin')
<td class="center">
<i class="glyphicon glyphicon-edit"></i> EDIT
</td>
<td class="center">
<form action="{{ route('Sale.destroy', ['id'=>$sale->id ]) }}" method="post" onsubmit="return confirm('Delete sale {{ $sale->name }} permanently?')" >
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button class="btn btn-danger btn-sm" type="submit" ><i class="glyphicon glyphicon-trash"></i> DELETE</button>
</form>
</td>
#else
<td class="center">
<b><p>Only for admin</p></b>
</td>
<td class="center">
<b><p>Only for admin</p></b>
</td>
#endif
</tr>
#endforeach
</tbody>
</table>
My controller is:
class SalesController extends Controller
{
public function index()
{
$sales=Sale::all();
return view('Sale.index')->with('sales',$sales);
}
public function create()
{
$items=Item::all();
return view('Sale.create')->with('items',$items);;
}
public function store(Request $request)
{
$this->validate($request, [
'item_id'=>'required|integer',
//'price'=>'required|regex:/^\d+(\.\d{1,2})?$/',
'quantity'=>'required|integer',
]);
$item=Item::FindOrFail($request->item_id);
$item->quantity -= ($request->quantity);
$sale=new Sale;
$sale->seller_id=$request->get('seller_id');
$sale->item_id=$item->id;
$sale->price=$item->selling_price * $request->input('quantity');
$sale->quantity=$request->input('quantity');
$sale->save();
$item->save();
return redirect('/Sale')->with('success','Sale added');
}
public function edit($id)
{
$sales=Sale::find($id);
return view('Sale.edit')->with('sales',$sales);
}
public function update(Request $request, $id)
{
$this->validate($request, [
//'price'=>'required|regex:/^\d+(\.\d{1,2})?$/',
'quantity'=>'required|integer',
]);
$sale=Sale::find($id);
$item=Item::FindOrFail($sale->item_id);
$item->quantity = $item->quantity + $sale->quantity - $request->quantity;
$sale->quantity=$request->input('quantity');
$sale->price=$item->selling_price * $request->input('quantity');
$item->save();
$sale->save();
return redirect('/Sale')->with('success','Sale updated');
}
public function destroy($id)
{
$sale = Sale::find($id);
$sale->delete();
return redirect('/Sale')->with('success','Sale Removed');
}
}
When I try to add a new item, it works well. But I cannot use the imported one.
Make sure you have id column in your sale table.
and you have create the relationship with your user model and item model in your migration file and sale model.
public function user()
{
return $this->belongsTo(User::class);
}
public function item()
{
return $this->belongsTo(Item::class); // assuming you have named the model "Item" for your item table.
}

Data not fetching of current user in laravel

I am trying to get the data of current log in user but i am getting the result of all users in database. While in all views same problem is accure please help.
My code is given
My view is personal.blade.php
#extends('layouts.app')
#section('content')
<div class="container"><br>
<h1 class="text-success text-center">Profile</h1><br>
<table class="table table-bordered">
#foreach($data as $value)
<tr>
<th>Name</th>
<td>{{ $value ->tname}}</td>
</tr>
<tr>
<td>Father Name</td>
<td>{{ $value ->fname}}</td>
</tr>
<tr>
<td>Email</td>
<td>{{ $value ->email}}</td>
</tr>
<tr>
<td>Official Email</td>
<td>{{ $value ->off_email}}</td>
</tr>
#endforeach
</table>
<div class="form-group">
<label>Generate Report</label>
<div class="radio form-control">
<label class="col-md-4"><input type="radio" name="status" value="conf" >Personal</label>
<label class="col-md-4"><input type="radio" name="status" value="general">Publications</label>
</div>
</div>
<button class="btn btn-info" data-toggle="collapse" data-target="#demo"> Generate PDF</button>
<button class="btn btn-info" data-toggle="collapse" data-target="#demo"> Generate CSV</button>
<button class="btn btn primary">Go to Home</button><br>
<div id="demo" class="collapse">
<h3 class="text-success text-center">Complete your publication's detail</h3><br>
<div class="col-md-offset-3 col-md-6 m-auto d-block">
<form action="pub" method="post">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div>
#endsection
My controller is EducationController.php and its code is given.
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\education;
use DB;
class EducationController extends Controller
{
public function show()
{
//
$data['data'] = DB::table('users')->get();
if(count ($data)>0){
return view('personal',$data);
}
else
{
return view('personal');
}
}
}
My route code is given here.
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/personal','EducationController#personal');
Please help me. I dont know how to use the current user in all views. I am login while in result I am getting the result of all users which is stored in database. thanks in advance.
You use a #foreach which implies you expect multiple users in your view.
If you only want to show details for the logged in user you should do:
<?php
class EducationController extends Controller
{
public function show()
{
if(\Auth::check()){
$user = \Auth::user();
return view('personal',compact('user'));
}
else
{
return view('personal');
}
}
}
And in your view:
#extends('layouts.app')
#section('content')
<div class="container"><br>
<h1 class="text-success text-center">Profile</h1><br>
<table class="table table-bordered">
#if (isset($user))
<tr>
<th>Name</th>
<td>{{ $user->tname}}</td>
</tr>
<tr>
<td>Father Name</td>
<td>{{ $user->fname}}</td>
</tr>
<tr>
<td>Email</td>
<td>{{ $user->email}}</td>
</tr>
<tr>
<td>Official Email</td>
<td>{{ $user->off_email}}</td>
</tr>
#endif
</table>
// Rest of view
It is because your code is actually for getting all users. You should do it like this :
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\education;
use DB;
class EducationController extends Controller
{
public function show()
{
$user = Auth::user();
return view('personal',compact('user'));
}
}
}
then in your view:
<tr>
<th>Name</th>
<td>{{ $user->tname}}</td>
</tr>
<tr>
<td>Father Name</td>
<td>{{ $user->fname}}</td>
</tr>
<tr>
<td>Email</td>
<td>{{ $user->email}}</td>
</tr>
<tr>
<td>Official Email</td>
<td>{{ $user->off_email}}</td>
</tr>
Note that if you have multiple auth, you must specify your guard :
Auth::guard('yourguard')->user();
otherwise, your user will return a null.

Categories