I am trying to check the given input is already existed between the c_start and c_end through query, but it is not working. Here is my controller.. for example if person 1 booked a room from 10 to 12 then person can't book the same room at same date from 11 to 12 or any time between the existing booked time.
/* namespace App\booking; */
namespace App\Http\Controllers;
use App\booking;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use DB;
use App\Quotation;
use DateTime;
class RoombookController extends Controller {
public function insert_check(Request $request) {
$roomname = $request->input('roomname');
$book = $request->input('bookdate');
$dbstime = explode(':', $request->input('starttime'));
$dbetime = explode(':', $request->input('endtime'));
$dbstime[0] = $dbstime[0] * 60;
$dbetime[0] = $dbetime[0] * 60;
$dbsum = array_sum($dbstime);
$dbesum = array_sum($dbetime);
$users = DB::table("bookings")
->select("id")
->where('bookdate', '=', $request->input('bookdate'))
->where('roomname', '=', $request->input('roomname'))
->where(function ($query){
$query->where('c_start', '<', $dbsum);
$query->orWhere('c_end', '>', $dbsum);
})
->orWhere(function($query){
$query->where('c_start', '<', $dbesum);
$query->orWhere('c_end', '>', $dbesum);
});
if ($users->count() == 0) {
$booking = new booking;
$booking->bookdate = $request->input('bookdate');
$booking->roomname = $request->input('roomname');
$booking->starttime = $startTime = $request->input('starttime');
$booking->endtime = $finishTime = $request->input('endtime');
$booking->purpose = $request->input('Purpose');
$booking->booked_by = Auth::user()->id;
$smstime = explode(':', $startTime);
$emstime = explode(':', $finishTime);
$smstime[0] = $smstime[0] * 60;
$emstime[0] = $emstime[0] * 60;
$startsum = array_sum($smstime);
$endsum = array_sum($emstime);
$booking_time = $startTime . ' to ' . $finishTime;
$booking->c_start = $startsum;
$booking->c_end = $endsum;
$booking->booking_time = $booking_time;
$time = ($etime - $stime) / 60;
$booking->total_duration = $time;
$booking->save();
return view("bookmessage");
} else {
return view("duplicateValue");
}
}
}
Change query to:
$users = DB::table("bookings")
->select("id")
->where('bookdate', '=', $request->get('bookdate'))
->where('roomname', '=', $request->get('roomname'))
->where(function ($query) use ($dbsum, $dbesum){
$query->where(function ($query) use ($dbsum){
$query->where('c_start','<',$dbsum);
$query->Where('c_end','>',$dbsum);
})
->orWhere(function($query) use($dbesum){
$query->where('c_start','<',$dbesum);
$query->orWhere('c_end','>',$dbesum);
});
});
Try this code and let me know if it works:
$whereCondition = array('bookdate'=>$request->input('bookdate'),'roomname'=>$request->input('roomname'));
$users = DB::table("bookings")
->select("id")
->where($whereCondition)
->where(function ($query use $dbsum){
$query->where('c_start','<',$dbsum);
$query->orWhere('c_end','>',$dbsum);
})
->orWhere(function($query use $dbesum){
$query->where('c_start','<',$dbesum);
$query->orWhere('c_end','>',$dbesum);
})
->get();
You can run your sql query directly in laravel query builder .You can try this:
$sql = "SELECT * FROM `bookings` WHERE `bookdate`='2016-12-27' AND `roomname`='3' AND (($dbsum>`c_start` AND $dbsum<`c_end`) OR ($dbesum>`c_start` AND $dbesum<`c_end`))";
$result = DB::select(DB::raw($sql))
$result variable contains your output. You must be use your DB class
use DB;
this is the query from which i got my correct result
$whereCondition = array('bookdate'=>$request->input('bookdate'),'roomname'=>$request->input('roomname'));
$users = DB::table("bookings")
->select("id")
->where('bookdate', '=', $request->get('bookdate'))
->where('roomname', '=', $request->get('roomname'))
->whereRaw(DB::raw("((c_start<$dbsum and c_end>$dbsum) or (c_start<$dbesum and c_end>$dbesum ))"))
->get();
Related
How to Assign or store Model's table name into a variable in laravel (this is for filter functionality)?
$query = new LiveClasses;
if (request('language')) {
// die("333");
$query->where('language_used', '=', request('language'));
}
if (request('start') && request('last')) {
// die("333");
$first = 'sub_price_1 >= ' . request('start');
$second = 'sub_price_1 <= ' . request('last');
$query->whereRaw($first)->whereRaw($second);
}
if (request('rating')) {
// die("&rating=5&start=150&last=1264");
$query
->leftJoin('reviews', 'reviews.reviewable_id', '=', 'live_classes.id')
->Where('rating', request('rating'))
->Where('reviewable_type', '=', 'App\Models\LiveClasses');
// $courses = Review::where('rating', request('rating'))
// ->leftJoin('live_classes', 'reviews.reviewable_id', '=', 'live_classes.id')
}
$courses = $query->paginate(9);
To get the name of model table use ->getTable() eloquent method.
To get the morphable class name (type) use ->getMorphClass() eloquent method.
$query = new LiveClasses;
if (request('language')) {
$query->where('language_used', '=', request('language'));
}
if (request('start') && request('last')) {
$first = 'sub_price_1 >= ' . request('start');
$second = 'sub_price_1 <= ' . request('last');
$query->whereRaw($first)->whereRaw($second);
}
if (request('rating')) {
$reviewTable = (new Review)->getTable();
$query
->leftJoin($reviewTable, reviewTable . '.reviewable_id', '=', $query->getTable() . '.id')
->where('rating', request('rating'))
->where('reviewable_type', '=', $query->getMorphClass());
}
$courses = $query->paginate(9);
How to convert this code to Laravel (Eloquent):
$query = 'SELECT * FROM posts p WHERE (p.is_public = 1)';
if (isset($date)){ //$date format is '2018-09-01 00:00:00'
$query .= ' AND (p.created_at > "'.$date.'")';
}
if (isset($search)){
$query .= ' AND ((p.title LIKE "%'.$search.'%") OR (p.body LIKE "%'.$search.'%"))';
}
try this:
assume Post is your model
$posts = Post::where('is_public', 1);
if (isset($date)) {
$posts->where('created_at', '>', $date);
}
if (isset($search)) {
$posts->where(function($query) use ($search) {
$query->where('title', 'like', "%'.$search.'%")
->orWhere('body', 'like', "%'.$search.'%");
});
}
$posts = $posts->get();
This is Example code : assume Post is your model
$getPosts=Post::query()->where('is_public',1);
$getPosts->when(isset($date),function($q) use ($date){
$q->where('created_at','>',$date);
});
$getPosts->when(isset($search),function($q) use ($search){
$q->where('title','like','%'.$search.'%');
$q->orWhere('body','like','%'.$search.'%');
});
$posts=$getPosts->get();
You should try this:
$query = Post::where('is_public', '1');
if (isset($date)){ //$date format is '2018-09-01 00:00:00'
$query->where('created_at', '>', $date);
}
if (isset($search)){
$query->whereRaw('title LIKE "%'.$search.'%" OR body LIKE "%'.$search.'%"');
}
$posts = $query->get();
I'm using Laravel 5.5.
I have Table centrals with Model Centrals
and table like this
my Controller
$from = $request->year_from;
$to = $request->year_to;
$month_from = $request->month_from;
$month_to = $request->month_to;
$param = $request->get('parameters_id', []);
$search = Centrals::whereIn('parameters_id', $param)
->where('type', 'Monthly')
->where('year', $from)
->whereBetween('months_id', [$month_from, $month_to])
->orderBy('year')
->get();
now how i get data
example request:
$request->year_from = 2016;
$request->month_from = 1; /* 1 =Jan*/
$request->year_from = 2018;
$request->month_from = 3; /* 3 =Mar*/
The following should do the trick:
$search = Centrals::whereIn('parameters_id', $param)
->where('type', 'Monthly')
->where(function($q) use ($yearFrom, $monthFrom) {
$q->where('year', '>', $yearFrom);
$q->orWhere(function($q2) use ($yearFrom, $monthFrom) {
$q2->where('year', $yearFrom);
$q2->where('month', '>=', $monthFrom);
});
})
->where(function($q) use ($yearTo, $monthTo) {
$q->where('year', '<', $yearTo);
$q->orWhere(function($q2) use ($yearTo, $monthTo) {
$q2->where('year', $yearTo);
$q2->where('month', '<=', $monthTo);
});
})->get();
I'm making a Laravel Pagination based from my query result and be rendered in my view. I'm following this guide http://laravel.com/docs/5.1/pagination but I get an error:
Call to a member function paginate() on a non-object
I'm using query builder so I think that should be ok? Here's my code
public function getDeliveries($date_from, $date_to)
{
$query = "Select order_confirmation.oc_number as oc,
order_confirmation.count as cnt,
order_confirmation.status as stat,
order_confirmation.po_number as pon,
order_summary.date_delivered as dd,
order_summary.delivery_quantity as dq,
order_summary.is_invoiced as iin,
order_summary.filename as fn,
order_summary.invoice_number as inum,
order_summary.oc_idfk as ocidfk,
order_summary.date_invoiced as di
FROM
order_confirmation,order_summary
where order_confirmation.id = order_summary.oc_idfk";
if (isset($date_from)) {
if (!empty($date_from))
{
$query .= " and order_summary.date_delivered >= '".$date_from."'";
}
}
if (isset($date_to)) {
if (!empty($date_to))
{
$query .= " and order_summary.date_delivered <= '".$date_to."'";
}
}
$query.="order by order_confirmation.id ASC";
$data = DB::connection('qds106')->select($query)->paginate(15);
return $data;
}
However when I remove the paginate(15); it works fine.
Thanks
in the doc at this page: http://laravel.com/docs/5.1/pagination
we can see that we are not forced to use eloquent.
$users = DB::table('users')->paginate(15);
but, be sure you don't make a groupBy in your query because, the paginate method uses it.
after i'm no sure you can use paginate with query builder ( select($query) )
--- edit
You can create collection an use the paginator class :
$collection = new Collection($put_your_array_here);
// Paginate
$perPage = 10; // Item per page
$currentPage = Input::get('page') - 1; // url.com/test?page=2
$pagedData = $collection->slice($currentPage * $perPage, $perPage)->all();
$collection= Paginator::make($pagedData, count($collection), $perPage);
and in your view just use $collection->render();
public function getDeliveries($date_from, $date_to)
{
$query="your_query_here";
$deliveries = DB::select($query);
$deliveries = collect($deliveries);
$perPage = 10;
$currentPage = \Input::get('page') ?: 1;
$slice_init = ($currentPage == 1) ? 0 : (($currentPage*$perPage)-$perPage);
$pagedData = $users->slice($slice_init, $perPage)->all();
$deliveries = new LengthAwarePaginator($pagedData, count($deliveries), $perPage, $currentPage);
$deliveries ->setPath('set_your_link_page');
return $deliveries;
}
You set it by using the custom pagination..
$query = "Your Query here";
$page = 1;
$perPage = 5;
$query = DB::select($query);
$currentPage = Input::get('page', 1) - 1;
$pagedData = array_slice($query, $currentPage * $perPage, $perPage);
$query = new Paginator($pagedData, count($query), $perPage);
$query->setPath('Your Url');
$this->data['query'] = $query;
return view('Your_view_file', $this->data, compact('query'));
Here you can specify the path by using the setpath().
In your View
#foreach($query as $rev)
//Contents
#endforeach
<?php echo $Reviews->appends($_REQUEST)->render(); ?>
The appends will append the data.
Thank you.
this is the way i did, it use query builder and get the same result with pagination
$paginateNumber = 20;
$key = $this->removeAccents(strip_tags(trim($request->input('search_key', ''))));
$package_id = (int)$request->input('package_id', 0);
$movieHasTrailer = MovieTrailer::select('movie_id')->where('status','!=','-1')->distinct('movie_id')->get();
$movieIds = array();
foreach ($movieHasTrailer as $index => $value) {
$movieIds[] = $value->movie_id;
}
$keyparams = array();
$packages = Package::select('package_name','id')->get();
$whereClause = [
['movie.status', '!=', '-1'],
['movie_trailers.status', '!=', '-1']
];
if(!empty($key)){
$whereClause[] = ['movie.title', 'like', '%'.$key.'%'];
$keyparams['search_key'] = $key;
}
if($package_id !== 0){
$whereClause[] = ['movie.package_id', '=', $package_id];
$keyparams['package_id'] = $package_id;
}
$movies = DB::table('movie')
->leftJoin('movie_package','movie.package_id','=','movie_package.id')
->leftJoin('movie_trailers','movie.id','=','movie_trailers.movie_id')
->where($whereClause)
->whereIn('movie.id',$movieIds)
->select('movie.*','movie_package.package_name','movie_trailers.movie_id as movie_id',
DB::raw('count(*) as total_trailers, movie_id')
)
->groupBy('movie.id')
->paginate($paginateNumber);
If you need to hydrate, you can do this...
$pages = DB::table('stuff')
->distinct()
->paginate(24, ['stuff.id']);
$stuffs = Stuff::hydrate($pages->items());
return view('stuff.index')->with('stuffs', $stuffs)->with('pages', $pages)
$stuffs will contain your model object, $pages will contain your pagination, probably not the most efficient, but it works.
// import those Class into your Laravel Controller
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Input;
use Illuminate\Database\Eloquent\Collection;
// In your public function
$query = DB::select(DB::raw("SELECT * FROM your_table"));
$collection = new Collection($query);
// Paginate
$perPage = 10; // Item per page
$currentPage = Input::get('page') - 1;
$pagedData = $collection->slice($currentPage * $perPage, $perPage)->all();
$pagination = new Paginator($pagedData, $perPage);
return response()->json([
$pagination
], 200);
I beg to excuse me for my poor english.
So, I have Laravel 5 ORM, and i need to make request that should add date to some rows, like MySQL DATE_ADD. Input is single date interval and array of id's, output is rows of database, that was changed by adding date interval. Ideally, it should be one ORM request. I know that it is possible to use "bad" way and get all rows, update it in a code, and insert to database, but imho it's not good.
I hope answer will be link to some help site or some code if it's does not complicate you. Thanks for your attention!
public function update($id)
{
$user_id = Auth::user()->id;
$rep_task = RepTask::find($id);
$cl_task = \Request::has('json') ? json_decode(\Request::input('json'),true) : \Request::all();
$ids = [];
$task_id = $rep_task->task_id;
$rep_tasks = RepTask::where('task_id', '=', $task_id)
->select('id')
->get();
$new_date = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['new_date']);
$selected_task_date = date_create_from_format(self::DATE_MYSQL_FORMAT, $rep_task->start_date);
$diff = date_diff($selected_task_date, $new_date);
if(\Request::has('json'))
{
$ids = [1,2,3]; //this for easy understanding
DB::table('rep_task')
->whereIn('id', $ids)
->update(['start_date' => DB::raw('DATE_ADD(start_date, INTERVAL ' . $diff->d . ' DAY)')]);
$out_json = ['updated' => $ids];
return json_encode($out_json, JSON_UNESCAPED_UNICODE);
}
else
{
$start_date = 0;
$end_date = 0;
if (!isset($cl_task['name']) || !isset($cl_task['text']))
return "{'error':'columns are not defined'}";
if (isset($cl_task['start_date']) && isset($cl_task['end_date']))
{
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['start_date']);
$start_date = $dt->format(self::DATE_MYSQL_FORMAT);
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT,$cl_task['end_date']);
$end_date = $dt->format(self::DATE_MYSQL_FORMAT);
}
$rep_task->name = $cl_task['name'];
$rep_task->text = $cl_task['text'];
$rep_task->start_date = $start_date;
$rep_task->end_date = $end_date;
$rep_task->users_id = $user_id;
$rep_task->save();
}
$user_id = Auth::user()->id;
$tasks = Task::getAllTasksByUserFullcalendar($user_id);
return view(
'task.index',
[
'tasks' => $tasks
]
);
}