I have building a laravel application where in a controller I'm checking with time overlapping problem.
The Logic I have used is in my controller's query first I will check whether the day_id has given as input is match with database with that day_id and then it will check with the time, if it matches so it can't let user to save the input otherwise if the query failed, it will let user to save the data.
public function postAllocateRoom(Request $request)
{
$startTime = Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('start')));
$endTime = Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('end')));
$dayId = $request->input('day_id');
$timeExists = ClassRoom::where('day_id', $dayId)
->andWhere('start', $startTime)
->andWhere('end', $endTime)
->exists();
if($timeExists){
return redirect('allocateRoomPage')->withErrors(['time' => 'Class Room Already Taken']);
}
$classRoom = new ClassRoom();
$classRoom->department_id=$request->input('department_id');
$classRoom->room_id=$request->input('room_id');
$classRoom->course_id=$request->input('course_id');
$classRoom->day_id=$dayId;
$classRoom->start=$startTime;
$classRoom->end=$endTime;
$classRoom->save();
$request->session()->flash('success', 'Successfully allocated room');
return redirect('allocateRoomPage');
}
But After I run the program I'm seeing the following Error:
BadMethodCallException in Builder.php line 2258: Call to undefined
method Illuminate\Database\Query\Builder::andWhere()
If anyone find the problem please help me to find the solution.
Simply use
$timeExists = ClassRoom::where('day_id', $dayId)
->Where('start', $startTime)
->Where('end', $endTime)
->exists();
as there is no andWhere method in laravel
There is no andWhere method.
Simple where(<...>)->where(<...>) acts like where <...> and where <...>.
Related
I have the following error in my code which I'm having trouble figuring out. I would appreciate if anyone could help. What I am trying to do is add validation to the working hours that have been input by an employee. In my create appointment form I have input the following details;
however the following error is returned;
Call to a member function provides_service() on null
in AppointmentsController.php (line 63)
I'm not sure why this is occurring as the data exists in my db;
AppointmentsController - store method
public function store(StoreAppointmentsRequest $request)
$employee = \App\Employee::find($request->employee_id);
$working_hours = \App\WorkingHour::where('employee_id', $request->employee_id)->whereDay('date', '=', date("d", strtotime($request->date)))->whereTime('start_time', '<=', date("H:i", strtotime("".$request->starting_hour.":".$request->starting_minute.":00")))->whereTime('finish_time', '>=', date("H:i", strtotime("".$request->finish_hour.":".$request->finish_minute.":00")))->get();
if($employee->provides_service($request->service_id))
return redirect()->back()->withErrors("This employee doesn't provide your selected service")->withInput();
if($working_hours->isEmpty())
return redirect()->back()->withErrors("This employee isn't working at your selected time")->withInput();
$appointment = new Appointment;
$appointment->client_id = $request->client_id;
$appointment->employee_id = $request->employee_id;
$appointment->start_time = "".$request->date." ".$request->starting_hour .":".$request->starting_minute.":00";
$appointment->finish_time = "".$request->date." ".$request->finish_hour .":".$request->finish_minute.":00";
$appointment->comments = $request->comments;
$appointment->save();
return redirect()->route('admin.appointments.index');
}
I have a Model in Larevel that is taking in parameters for reporting total units in the database.
I want to be able to filter the units returned based on the $entity_ids and the $start and $end dates selected by the user.
entity_ids is working fine with a simple whereIn() method call, but the dates are causing some issue.
My code in Order.php Model is below:
public static function getAllOrdersForReporting($entity_ids, $start, $end) {
$orders = Order::select('all order information entered here')
->whereIn('orders.entity_id', $entity_ids)
->when($start && $end, function ($query, $start, $end) { //<-- Error Thrown Here
return $query->whereBetween('order_date', [$start, $end]);
})
->join('entities', 'entities.id', '=', 'ura_orders.entity_id')
->join('entity_address_information', 'entity_address_information.entity_id', '=', 'ura_orders.entity_id')->distinct()->get();
return $orders;
}
In my ReportingController.php I am entering in the following:
public function displayUnits() {
$entities = request()->entities_ids;
$start = request()->start_date;
$end = request()->end_date;
$orders = Ura_order::getAllOrdersForReporting($entities, $start, $end);
return view('reporting.pages.units', compact('entities', 'start', 'end', 'orders'));
}
However when I run this, I get the following error:
Too few arguments to function
App\Models\Order::App\Models{closure}(), 2 passed in
C:\xampp\htdocs\mywebsite\vendor\laravel\framework\src\Illuminate\Database\Concerns\BuildsQueries.php
on line 91 and exactly 3 expected
Not exactly sure what this error means, except that the Model is seeing only 2 errors passed in and it expected 3.
I marked the line where it is throwing the error up above in the code.
Any advice on how to get this to work? I know the 3rd parameter for when() is supposed to be a callback function, but not sure how to make this work.
You have to use variables in your callback function:
->when($start && $end, function ($query) use ($start, $end) {
return $query->whereBetween('order_date', [$start, $end]);
})
You can try with this code:
->when($start && $end, function ($query, $condition) use($start, $end) {
return $query->whereBetween('order_date', [$start, $end]);
})
As already pointed in the comments the tihrd parameter of a when() should be a function, with the use() statement you can pass the variables in the closure.
I'm not able to fix this error when I tried associate category to transaction.
// TransactionController
$transactions = DB::table('transactions')
->where('status', 'false')
->orderBy('date','asc')
->get();
foreach($transactions as $data) {
$transaction = new Transaction();
$transaction->id = $data->id;
$transaction->category = Transaction::find($data->categories_id)->category;
$transaction->description = $data->description;
}
The error occurs at time:
ErrorException in TransactionController.php line 80:
Trying to get property of non-object
Line 80: $transaction->category = Transaction::find($data->categories_id)->category;
But, if I test my code with die, that's result:
die(Transaction::find($data->categories_id)->category()->first());
{"id":1,"users_id":1,"description":"Alimenta\u00e7\u00e3o","created_at":"2016-11-15 20:31:11","updated_at":"2016-11-15 20:31:11"}
// Transaction Model
class Transaction extends Model
{
public function category(){
return $this->hasOne('App\Category','id');
}
[]'s
You are getting that error as one or multiple $data->categories_id are not matching the id on the transactions table.
Note:
It's not a good practice to find a model and call a function on it on the same line as you have done.
Transaction::find($data->categories_id)->category;
Because, you never know what id will be passed as argument to find().
Better go for findOrFail().
$tran = Transaction::findOrFail($data->categories_id);
$cat = $tran->category;
The findOrFail() function will throw a ModelNotFoundException whenever the id doesn't match in the transactions table. This exception can be easily handled by try...catch block.
I have building a laravel controller where I'm trying to avoid time overlapping. But I'm facing problem with my query as I couldn't run the query properly in my controller:
public function postAllocateRoom(Request $request)
{
$classRoom = new ClassRoom();
$classRoom->department_id=$request->Input(['department_id']);
$classRoom->room_id=$request->Input(['room_id']);
$classRoom->course_id=$request->Input(['course_id']);
$classRoom->day_id=$request->Input(['day_id']);
$classRoom->start=Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('start')));
$classRoom->end=Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('end')));
$day = $classRoom->day_id;
$startTime=$classRoom->start;
$endTime=$classRoom->end;
$result=DB::select( DB::raw("SELECT * FROM `allocate_rooms`
WHERE start='$startTime' AND end='$endTime' AND day_id='day'"));
if (sizeof($result)>0) {
flash()->error('Class Room Already Taken.');
return redirect('allocateRoomPage');
}
else {
$classRoom->save();
flash()->success('Successfully allocated room.');
return redirect('allocateRoomPage');
}
}
Here in my controller's query first I will check whether the day_id has given as input is match with database with that day_id and then it will check with the time, if it matches the result will be more than one, so it can't let user to save the input otherwise if the query failed, it will let user to save the data.
I'm facing problem with the query. If any one help to find out the solution.
First of all, I suggest you to perform some validations on your inputs before creating the model instance.
Then, I don't understand why you sometimes use $request->Input(['input_name']) and sometimes $request->input('input_name'), it's better to use the second syntax.
I edited your code, please test it, it should work.
public function postAllocateRoom(Request $request)
{
// SOME VALIDATION HERE BEFORE GO ON, PLEASE
$startTime = Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('start')));
$endTime = Carbon::parse(str_replace(array('am', 'pm'), ':00', $request->input('end')));
$dayId = $request->input('day_id');
$timeExists = AllocateRooms::where('day_id', $dayId)
->where('start', $startTime)
->where('end', $endTime)
->exists(); //use allocate_rooms table model (I don't know if it is ClassRomm)
if($timeExists){
reuturn redirect('allocateRoomPage')->withErrors(['time' => 'Class Room Already Taken']);
}
$classRoom = new ClassRoom();
$classRoom->department_id=$request->input('department_id');
$classRoom->room_id=$request->input('room_id');
$classRoom->course_id=$request->input('course_id');
$classRoom->day_id=$dayId;
$classRoom->start=$startTime;
$classRoom->end=$endTime;
$classRoom->save();
$request->session()->flash('success', 'Successfully allocated room');
return redirect('allocateRoomPage');
}
This work perfect:
public function scopeHBO($query)
{
return $query ->where('network', '=', "hbo");
}
Call in Controller: It Works!
$events = Schedule::HBO()->orderBy('searchdate')->get();
When I add another Query Scope like so:
public function scopeHBO($query)
{
return $query
->where('network', '=', "hbo")
->where('searchdate', '>=', 'NOW()');
}
OR:
public function scopeDate($query)
{
return $query->where('searchdate', '>= ', 'NOW()');
}
Then call in the controller:
$events = Schedule::HBO()->Date()->orderBy('searchdate')->get();
I get an error: Undefined variable: event. I tried with with Raw MySql in the same model and it works. Whenever i add a query scope, does not matter what it is.. i get that same error Undefined variable: event.
NOW() is a function, so you need to use a raw query:
where('searchdate', '>=', DB::raw('NOW()'))
Then you can use the scopes. (Do note that I think scopeDate must be called as date(), not Date() - not 100 % sure on that though.)
This sounds less like a generic problem with Laravel, and more like a problem with you specific application.
My guess (which is a wild guess), is that adding that second where clause in your scope method
return $query
->where('network', '=', "hbo")
->where('searchdate', '>=', 'NOW()');
ended up creating a SQL query that returned 0 rows. Then, somewhere in your other code you're doing something like
foreach($events as $event)
{
//...
}
//referencing final $event outside of loop
if($event) { ... }
As I said, this is a wild guess, but the problem doesn't seem to be your query code, the problem seems to be the rest of your code that relies on the query returning a certain number of, or certain specific, rows/objects.