Laravel - How to use a single textbox for global search - laravel

I have this Laravel-5.8 code whereby users can search using different control fields to search for employee_code, designation and department.
class HrEmployee extends Model
{
protected $table = 'hr_employees';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'employee_code',
'address',
'email',
'employee_designation_id',
'first_name',
'emp_image',
'last_name',
'other_name',
'department_id',
];
protected $appends = ['full_name'];
public function user()
{
return $this->belongsTo('App\User');
}
public function designation()
{
return $this->belongsTo('App\Models\Hr\HrDesignation','employee_designation_id');
}
public function department()
{
return $this->belongsTo('App\Models\Hr\HrDepartment','department_id');
}
}
Controller
public function index(Request $request)
{
$userCompany = Auth::user()->company_id;
$render=[];
$employees = HrEmployee::where('company_id', $userCompany);
$employees=$employees->with('department','designation');
if(isset($request->employee_code))
{
$employees=$employees->where('employee_code','like','%'.$request->employee_code.'%');
$render['employee_code']=$request->employee_code;
}
if(isset($request->employee_designation_id))
{
$employees=$employees->where('employee_designation_id',$request->employee_designation_id);
$render['employee_designation_id']=$request->employee_designation_id;
}
if(isset($request->department_id))
{
$employees=$employees->where('department_id',$request->department_id);
$render['department_id']=$request->department_id;
}
$employees= $employees->paginate(6);
$employees= $employees->appends($render);
$data['employees'] = $employees;
$data['departments']= HrDepartment::where('company_id', $userCompany)->pluck('dept_name','id');
$data['designations']= HrDesignation::where('company_id', $userCompany)->pluck('designation_name','id');
return view('hr.employees.index',$data);
}
view
{{ Form::model(request(),['method'=>'get']) }}
<div class="row" style="margin-bottom: 10px">
<div orm-group class="col-sm-3">
{{Form::label('employee_code', 'Employee No.')}}
{{ Form::text('employee_code',null,['class'=>'form-control','placeholder'=>'Employee Code']) }}
</div>
<div class="col-sm-4">
{{Form::label('department_id', 'Department')}}
{{ Form::select('department_id',$departments,null,['class'=>'form-control select2bs4','placeholder'=>'Select Department']) }}
</div>
<div class="col-sm-4">
{{Form::label('employee_designation_id', 'Designation')}}
{{ Form::select('employee_designation_id',$designations,null,['class'=>'form-control select2bs4','placeholder'=>'Select Designation']) }}
</div>
<div class="col-xs-3">
<br>
{{ Form::submit('Search',['class'=>'btn btn-warning']) }}
</div>
{{ Form::close() }}
</div>
<br>
<!-- Default box -->
<div class="card card-solid">
<div class="card-body pb-0">
<div class="row d-flex align-items-stretch">
#if (count($employees))
#foreach($employees as $key => $employee)
<div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch">
<div class="card bg-light">
<div class="card-header text-muted border-bottom-0">
{{isset($employee->designation) ? $employee->designation->designation_name : ''}}
</div>
<div class="card-body pt-0">
<div class="row">
<div class="col-7">
<h2 class="lead"><b>Staff ID: {{$employee->employee_code}}</b></h2>
<h2 class="lead"><b>{{$employee->first_name}} {{$employee->last_name}}</b></h2>
<h6 class="lead"><b>Employee Department: </b>{{isset($employee->department) ? $employee->department->dept_name : ''}}</h6>
<h6 class="lead"><b>Employment Date: </b>{{$employee->employment_date ? Carbon\Carbon::parse($employee->employment_date)->format('d-m-Y') : 'N/A' }}</h6>
<ul class="ml-4 mb-0 fa-ul text-muted">
<li class="small"><span class="fa-li"><i class="fas fa-lg fa-envelope"></i></span> Email: {{$employee->email}}</li>
<li class="small"><span class="fa-li"><i class="fas fa-lg fa-phone"></i></span> Phone #: {{isset($employee->phone) ? $employee->phone : 'N/A'}}</li>
</ul>
</div>
<div class="col-5 text-center">
#if($employee->emp_image != '')
<img src="{{ URL::to('/') }}/public/storage/employees/image/{{ $employee->emp_image }}" class="img-circle img-fluid" />
#else
<img class="profile-user-img img-fluid img-circle" src="{{asset('theme/adminlte3/dist/img/default.png')}}" alt="" class="img-circle img-fluid">
#endif
</div>
</div>
</div>
<div class="card-footer">
<div class="text-right">
#can('employee_show')
<a href="{{ route('hr.employees.show', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
<i class="fas fa-user"></i> View Detail
</a>
#endcan
</div>
</div>
</div>
</div>
#endforeach
#else
<h4 style="text-align:center;">No matching records found</h4>
#endif
</div>
</div>
<!-- /.card-body -->
<div class="card-footer align-items-center d-flex justify-content-center">
{{ $employees->links() }}
<!-- /.card-footer -->
</div>
<!-- /.card -->
</div>
Instead of searching for each field one by one using different control fields. How do I use a sing textbox to search for employee_code, first_name, last_name, department and designation?
Thank you

You can do it with below code:
$searchText = $request->searchText;
$employees = HrEmployee::with(['department','designation'])->where('company_id', $userCompany);
if($searchText)
{
$employees->where(function ($query) use($searchText) {
$query->where('employee_code','like','%'.$searchText.'%')
->orWhere('first_name','like','%'.$searchText.'%')
->orWhere('last_name','like','%'.$searchText.'%')
->orWhereHas('designation', function($q) use ($searchText) {
$q->where('designation_name', 'like','%'.$searchText.'%');
})
->orWhereHas('department', function($q) use ($searchText) {
$q->where('department_name', 'like','%'.$searchText.'%');
});
});
}
$employees = $employees->get();
// For pagination
// $employees = $employees->paginate(6);
Here designation_name is name field in designation table and department_name is name field in designation table.

{{ Form::model(request(),['method'=>'get']) }}
<div class="row" style="margin-bottom: 10px">
<div orm-group class="col-sm-3">
{{Form::label('search', 'Search')}}
{{ Form::text('search',null,['class'=>'form-control','placeholder'=>'search']) }}
</div>
<div class="col-xs-3">
<br>
{{ Form::submit('Search',['class'=>'btn btn-warning']) }}
</div>
{{ Form::close() }}
then your controller function use orwhere()
public function index(Request $request)
{
$search = $request->search;
$userCompany = Auth::user()->company_id;
$render=[];
$employees = HrEmployee::where('company_id', $userCompany);
$employees=$employees->with('department','designation');
$employees=$employees->where('employee_code','like','%'.$search.'%')
->orWhere('employee_designation_id',$search)
->orwhere('department_id',$search)
->paginate(6);
$data['employees'] = $employees;
$data['search'] = $search;
$data['departments']= HrDepartment::where('company_id', $userCompany)->pluck('dept_name','id');
$data['designations']= HrDesignation::where('company_id', $userCompany)->pluck('designation_name','id');
return view('hr.employees.index',$data);
}

Related

How to fetch next record from DB when a user submits Answer or Time is finished in laravel 8?

Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Events extends Model
{
use HasFactory;
use SoftDeletes;
public function EventQues()
{
return $this->hasMany(Questions::class, 'event_id')->limit(1);
}
}
Controller
public function ActiveEvent()
{
$display = Events::where('status', 1)->with('EventQues')->first();
// $next = Questions::where('id', '>',$request->id)->where('is_deleted',0)->first('id');
return view('frontend.index', compact('display'));
}
// function for front send answer value to DB
public function getData(Request $request)
{
$value = $request->all();
return response()->json($value, 200);
}
view
#extends('frontend.master')
#section('title', 'Home')
#section('content')
{{-- top menu Start --}}
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand text-uppercase font-weight-bold" href="#">Logo</a>
<div class="col-2">
<h5 class=" dropdown-toggle text-light" id="navbarDropdownMenuLink" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">{{ Auth::user()->name }}</h5>
<div class="dropdown-menu mt-1" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="{{ route('twitch.logout') }}">Log Out</a>
</div>
</div>
</div>
</nav> {{-- top menu end --}}
<div class="container-fluid">
<div class="row">
<div class="card shadow col-lg-8 col-md-8 col-sm-12 m-4">
<div class="card-body ">
<div id="twitch-embed"></div>
</div>
</div>
<div class="card shadow col-lg-3 col-md-3 col-sm-12 m-4">
<div class="card-body">
<div id="list-example" class="list-group mt-2">
#if (!$display)
<h2 class="font-weight-bold mt-5" id="Nothing">Currently No Event Is Active</h2>
#else
<h3 class="font-weight-bold p-2 text-light text-center bg-primary">{{ $display->title }}</h3>
<p class="text-justify">{{ $display->description }}</p>
{{-- Displaying questions of Active event from database --}}
<h4 class="text-center p-2">Time :<span id="timer"> </span></h4>
#foreach ($display->EventQues as $data)
<div id="quesDiv"></div>
<div id="quesDiv1">
<h5 id="question">{{ $data->question }}</h5>
<form >
#csrf
<div class="btn btn-group-toggle d-flex flex-column" id="radioDiv"
data-toggle="buttons">
<label class="btn btn-secondary mb-2">
<input type="radio" name="options" id="option_a1" class="answer-check-box"
autocomplete="off" data-value="1"> Yes
</label>
<label class="btn btn-secondary">
<input type="radio" name="options" id="option_a2" class="answer-check-box"
autocomplete="off" data-value="2"> NO
</label>
</div>
</form>
</div>
#endforeach
#endif
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
#include('frontend.script')
#endsection
Script.js
$('#option_a1,#option_a2').click(function() {
if (options = $("input[type='radio']:checked")) {
val = options.attr('data-value');
} else if (options = $("input:checkbox:not(:checked)")) {
val = "";
}
});
let interval = setInterval(req, 1000);
function req() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if (val || timeleft < '0') {
$.ajax({
type: "post",
url: "{{ route('ajax') }}",
data: {
'id': '{{ $data->id }}',
'value': val
},
success: function(data) {
$('#quesDiv1').hide();
$('#quesDiv').html('Next Question');
},
error: function(data) {
console.log('error!!')
}
});
var timeOut = setTimeout(interval, 1000);
}
// clearInterval(interval);
}
I am making an app where I have made one to many relation between events and questions. When an event is active questions related to this event are displayed one at a time and when a user submits an answer then fetch the next question from Database. And I was using Ajax call for this.

Eloquent relationship through 2 models

I have Post model:
class Post extends Model
{
use HasFactory;
protected $fillable = [
'category_id',
'user_id',
'img',
'title',
'content',
];
public function user(){
return $this->belongsTo(User::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
public function comments(){
return $this->hasMany(Comment::class)->where('parent_id', '0');
}
}
Comments model:
class Comment extends Model
{
use HasFactory;
protected $fillable = [
'post_id',
'user_id',
'parent_id',
'content',
// 'img'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function replies()
{
return $this->hasMany(Comment::class,'parent_id');
}
}
Can I use the replies function via the post model?
For example:
#foreach($comments->comments->replies->sortByDesc('id') as $comment)
#endforeach
I am just trying to add replies to comments.
<div class="col-md-12">
<div class="blog-comment">
<hr/>
<ul class="comments">
<li class="clearfix">
#foreach($post as $comments)
#foreach($comments->comments->sortByDesc('id') as $comment)
<img src="https://bootdey.com/img/Content/user_1.jpg" class="avatar">
<div class="post-comments">
<p class="meta d-flex justify-content-between">{{ $comments->user->name }}<span>{{ $comments->user->created_at }}</span></p>
<p>
{{ $comment->content }}
</p>
</div>
<form action="{{ route('comment.store') }}" method="POST" class="w-100">
#csrf
<div class="replyform d-flex mb-3">
<input type="hidden" name="post_id" value="{{ $comments->id }}">
<input type="hidden" name="parent_id" value="{{ $comment->id }}">
<input class="d-block ml-auto w-50 align-top" type="text" name="content" required>
<button type="submit" class="offset replysub fas fa-paper-plane ml-1"></button>
</div>
</form>
#endforeach
#endforeach
#foreach($comments->comments->replies->sortByDesc('id') as $comment)
#if($comment->parent_id !== 0)
<ul class="comments">
<li class="clearfix">
<img src="https://bootdey.com/img/Content/user_3.jpg" class="avatar">
<div class="post-comments">
<p class="meta">Dec 20, 2014 JohnDoe says : <i class="pull-right"><small>Reply</small></i></p>
<p>
{{ $comment->content }}
</p>
</div>
<input class="replyform d-block ml-auto mb-3 w-50" type="text" name="" value="">
</li>
</ul>
#endif
#endforeach
</li>
</ul>
</div>
</div>
Of course, I can take and pass one more variable to the template, but I heard that you shouldn't do this, it overloads the controller. Therefore, I try to do it through an eloquent relationship.
P.S. Or is there a way to do it in the post model? Like:
public function replies(){
return $this->hasMany(Comment::class)->where('parent_id', 'id(of parent comment)');
}

Laravel Error - Route [appraisal.appraisal_goals.manager_employee_goal/{id?}] not defined

In Laravel-5.8 project, From this controller:
public function manager_employee_goal($id)
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
$linemanager = DB::table('hr_employees')->select('line_manager_id')->where('id', $userEmployee)->first();
$linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->pluck('id');
$appraisedemployees = HrEmployee::select('id', 'employee_code', 'first_name', 'last_name')->where('id', $id)->get();
$goals = AppraisalGoal::where('employee_id', $id)->where('appraisal_identity_id', $identities->id)->where('is_published', 1)->where('id', '!=', $linemanager->line_manager_id)->get();
return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals)->with('appraisedemployees', $appraisedemployees);
}
I navigaed to:
public function manager_employee_goal_list($id)
{
$goal = AppraisalGoal::findOrFail($id);
$goaldetails = AppraisalGoalDetail::where('appraisal_goal_id', $id)->get();
$goalcomments = AppraisalGoalComment::where('appraisal_goal_id', $id)->get();
return view('appraisal.appraisal_goals.manager_employee_goal_list')
->with('goal', $goal)
->with('goaldetails', $goaldetails)
->with('goalcomments', $goalcomments);
}
using:
<a class="btn btn-xs btn-primary" href="{{ route('appraisal.appraisal_goals.manager_employee_goal_list', ['id'=>$goal->id]) }}">
{{ trans('global.view') }}
</a>
When I wanted to navigate back to:
public function manager_employee_goal($id)
I used:
<div class="panel-heading clearfix">
<div class="container-fluid">
<div class="float-right">
<div class="btn-group btn-group-sm" role="group">
<a href="{{ route("appraisal.appraisal_goals.manager_employee_goal/{id?}") }}" class="btn bg-navy margin" title=" Back">
<span> Back to List</span>
</a>
</div>
</div>
</div>
</div>
But I got this error:
Route [appraisal.appraisal_goals.manager_employee_goal/{id?}] not defined
These are my route/web.php:
Route::get('appraisal_goals/manager_employee_goal/{id?}', 'Appraisal\AppraisalGoalsController#manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
Route::get('appraisal_goals/manager_employee_goal_list/{id?}', 'Appraisal\AppraisalGoalsController#manager_employee_goal_list')->name('appraisal.appraisal_goals.manager_employee_goal_list');
How do I resolve it?
Thank you
Just pass employee_id from goal it will fixed.
<div class="panel-heading clearfix">
<div class="container-fluid">
<div class="float-right">
<div class="btn-group btn-group-sm" role="group">
<a href="{{ route("appraisal.appraisal_goals.manager_employee_goal",['id'=>$goal->employee_id]) }}" class="btn bg-navy margin" title=" Back">
<span> Back to List</span>
</a>
</div>
</div>
</div>
</div>

i want to get a video id so that it can help me get comments related to that video in my site, it only displays a video but not comments

The biggest issue here is how to get these comments using the videoid in my bladeview -- my blade
<div id="videoid">{{$id->id}}</div>
<div id="videotitle">{{$id->title}}</div>
#php($comments = \App\comments::where('video_id','{{$id->id}}')->get() )
<div id="displaycomment">
#foreach($comments as $comment)
<div id="username">
<div id="con"><h6>{{$comment->id }}</h6></div>
<div id="con"><h6>{{$comment->user_id }}</h6></div>
<div id="con">{{$comment->created_at }}</div>
</div>
<div id="comment">{{$comment->comment }}</div>
#endforeach
</div>
My controller works well --
mycontroller
public function watch($id)
{
return view('video/watch', compact('id'));
}
This is your blade. Thought there's no need to query from the view but rather from the controller.
<div id="videoid">{{ $video->id }}</div>
<div id="videotitle">{{ $video->title }}</div>
<div id="displaycomment">
#foreach($comments as $comment)
<div id="username">
<div id="con"><h6>{{$comment->id }}</h6></div>
<div id="con"><h6>{{$comment->user_id }}</h6></div>
<div id="con">{{$comment->created_at }}</div>
</div>
<div id="comment">{{$comment->comment }}</div>
#endforeach
</div>
Then from your controller you can fetch your data and pass them to the view using Laravel's magic method:
public function watch($video_id)
{
$video = Video::whereId($video_id)->first();
$comments = \App\comments::where('video_id',$video_id)->get()
return view('video/watch',[
'video'=>$video,
'comments'=>$comments
]);
}
in controller
public function watch($id)
{
$video = Video::with('comments')->find($id);
$comments = \App\comments::where('video_id','{{$video->id}}')->get()
return view('video/watch', compact('video','comments'));
}
in view
<div id="videoid">{{$video->id}}</div>
<div id="videotitle">{{$video->title}}</div>
<div id="displaycomment">
#foreach($comments as $comment)
<div id="username">
<div id="con"><h6>{{$comment->id }}</h6></div>
<div id="con"><h6>{{$comment->user_id }}</h6></div>
<div id="con">{{$comment->created_at }}</div>
</div>
<div id="comment">{{$comment->comment }}</div>
#endforeach
</div>
You seem to be missing a key part of using Eloquent.
Relationships.
// Video model:
public function comments()
{
return $this->hasMany(Comment::class);
}
// Comment model:
public function video()
{
return $this->belongsTo(Video::class);
}
// Controller code: (Switched to [Route-model binding][2])
public function watch(Video $video)
{
return view('video.watch', [
'video' => $video
]);
}
// Update routes for Route-model-binding
Route::get('/watch/{video}', 'VideoController#watch')->name('video.watch');
// View:
<div id="videoid">{{$video->id}}</div>
<div id="videotitle">{{$video->title}}</div>
<div id="displaycomment">
#foreach ($video->comments as $comment)
<div id="username">
<div id="con">
<h6>{{$comment->id }}</h6>
</div>
<div id="con">
<h6>{{ $comment->user_id }}</h6>
</div>
<div id="con">$comment->created_at</div>
</div>
<div id="comment">$comment->comment</div>
#endforeach
</div>
Route-model binding

Using 2 Controller Functions in a View in Laravel

I want to have two loops in my view, so I wrote these two functions
public function index()
{
$books = Book::orderBy('created_at', 'desc')->take(10)->get();
return view('bookpage')->with('books', $books);
}
public function loggedin()
{
$books = Book::orderBy('RAND()')->take(1)->get();
return view('bookpage')->with('books', $books);
}
In the view I have
<!--First Loop -->
#foreach($books as $book)
<div class="col-md-6">
<div class="out-box">
<h2>{{ $book->name }}</h2>
<h3>{{ $book->author->name }}</h3>
<br>
Start Reading<br><br>
<img src="assets/img/cart-buy.png" width="13px"/> Buy
</div>
</div>
</div>
</div>
<div class="col-md-6">
<input id="aboutbook" type="radio" name="tabs" checked>
<label for="aboutbook" class="aboutbook">About This Book</label>
<input id="bookreview" type="radio" name="tabs">
<label for="bookreview" class="bookreview">Reviews</label>
<hr style="background-color:black;">
<section style="padding-top:5px;" id="bookabout" >
<div class="row">
<div class="col-md-12">
<p>{{ $book -> about }}</p>
<h1>About the Author</h1>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-md-3 col-6">
<img src="assets/img/Ellipse.png" class="rounded-circle" width="120px">
</div>
<div class="col-sm-4 col-md-4 col-6">
<h1>{{ $book->author->name }}</h1>
<h4>{{ $book->author->about }}</h4>
</div>
<div class="col-sm-4 col-md-5">
<div id="learnbtn">
Learn More
</div>
</div>
</div>
</section>
<section style="padding-top:5px;" id="bookabout1" >
jjjjjjj
</section>
</div>
</div>
</div>
#endforeach
</section>
<!--Second Loop -->
#foreach($books as $book)
#if($book->recommended === 1)
<div class="col-1-5">
<div class="home-catalog-image">
<a href="{{ $book->image_url }}" target="_blank">
<!-- <img src="{{ $book->image }}" alt="trending image" /> -->
<img src="{{ $book->image_url }}" class="img-responsive" alt="{{ $book->image_url }}">
</a>
<!-- <img src="{{ asset('/books/'.$book->image) }}" alt="trending image" /> -->
</div>
<p class="author">{{ $book->author->name }}</p>
<h1 class="book-title">{{str_limit($book -> name, 20) }}</h1>
</div>
#endif
#endforeach
In my web.php
Route::get('/', 'WelcomeController#index')->name('welcome');
I want to call another function in the view, although I know the method is wrong, I don't know how to go about it.
You don't have to create two different method for logged in user just use
public function index()
{
if(auth()->user()) {
$books = Book::orderBy('RAND()')->take(1)->get();
} else $books = Book::orderBy('created_at', 'desc')->take(10)->get();
return view('bookpage')->with('books', $books);
}
in view file use
#auth
//code for logged in user
#else
//code for guest user
#endauth
I was able to solve my problem like this
public function loggedin()
{
$data = array();
$data['recommends'] = Book::where('recommended', 1)->take(10)->get();
$data['latests'] = Book::orderBy('created_at', 'desc',)->where('recommended', 0)->take(10)->get();
$data['logged'] = Book::all()->random(1);
return view('index-logged', compact("data"));
}
In my view, I did
#foreach($data['logged'] as $log)
<h1>{{ $log->author->name }}</h1>
<h4>{{ $log->author->about }}</h4>
#endforeach
#foreach($data['recommends'] as $recommend)
<p class="author">{{ $recommend->author->name }}</p>
<h1 class="book-title">{{str_limit($recommend -> name, 20) }}</h1>
#endforeach
#foreach($data['latests'] as $latest)
<p class="author">{{ $latest->author->name }}</p>
<h1 class="book-title">{{str_limit($latest -> name, 20) }}</h1>
#endforeach

Resources