Access variable from other function LARAVEL - laravel

I'm trying to use the returned result from a function into another function. Here is my first function:
public function availableRooms(){
if(isset($_POST['selectedDate'])){
$checkInDateReceived = str_replace('/', '-', $_POST['selectedDate']);
$checkInDate = date('Y-m-d', strtotime($checkInDateReceived));
$availableRooms = DB::table('rooms')
->leftJoin('reservations', function ($secondJoin) use($checkInDate) {
$secondJoin->where('reservations.checkout_date', '<', $checkInDate);
})
->leftJoin('reservation_room_rel', function ($firstJoin) {
$firstJoin
->on('reservation_room_rel.room_id', '=', 'rooms.id')
->on('reservation_room_rel.reservation_id', '=', 'reservations.id');
})
->where([
['rooms.status', '=', 1]
])
->whereNull('reservation_room_rel.room_id')
->get();
return $availableRooms;
}
}
And here is my second function:
public function returnAddReservation(){
$availableRoomsRet = $this->availableRooms();
$mealSupplement = new Meal;
$accommodationSupplement = new AccommodationSupplement;
$accommodationSupplements = $accommodationSupplement::where('status', 1)
->orderBy('name', 'asc')
->get();
$mealSupplements = $mealSupplement::where('status', 1)
->orderBy('name', 'asc')
->get();
return view('addReservation', [
'availableRooms' => $availableRoomsRet,
'accommodationSupplements' => $accommodationSupplements,
'mealSupplements' => $mealSupplements
]);
}
First function returns correct result if it runs independently, but, when I dd($availableRoomsRet)it returns null.
Any idea how to access properly $availableRooms from public function availableRooms() into public function returnAddReservation() ?
Thanks!

Related

How to fetch data from the database in 2 different tables in Laravel Controller?

I don't know how to add $countries to the State queryString below. Could you help me
public function index(){
// $countries = Country::all();
$perPage = Requests::input('perPage') ?: 5;
return Inertia::render('State/Index',[
'states' => State::query()
->when(Requests::input('search'), function($query, $search){
$query->where('name', 'like', "%{$search}%");
})
->paginate($perPage)
->withQueryString(),
'filters' => Requests::only(['search', 'perPage']),
]);
}
You are missing $search variable.
And ->when($condition, function ...) need a true/false condition.
public function index(Request $request){
// $countries = Country::all();
// probably best to add validation at this point
$validated = $request->validate($rules);
$perPage = $request->input('perPage', 5); // set 5 as default when empty
$search = $request->input('search');
return Inertia::render('State/Index',[
'states' => State::query()
->when(!empty($search), function($query, $search){
$query->where('name', 'like', "%{$search}%");
})
->paginate($perPage)
->withQueryString(),
'filters' => $request->only(['search', 'perPage']),
]);
}

laravel inside with leftjoin is not working

I have added left join inside with but it is not working at all.
Please suggest or guide.
$q = $q->leftJoin('product_sort_order', function ($join) {
$join->on('products.id', '=', 'product_sort_order.product_id');
$join->on('products.sub_category_id', '=', 'product_sort_order.type_id');
})->orderBy('product_sort_order.sort_order', 'ASC');
Controller code (trying to get category products with relationship)
$category = Category::query();
$category->where('status', '=', '1');
$category->where('id', $sub_category_id);
// $category->where('status', '!=', '2');
$category = $category->with([
'subproducts' => function ($q) use ($request, $sub_category_id) {
$q->select('products.*');
$q->where('products.status', '=', 1);
$q->where('products.is_pendding', '=', 0);
$q->where('products.sub_category_id', $sub_category_id);
if ($request->get('theme')) {
$q->Where('products.theme_id', 'LIKE', '%' . $request->get('theme') . '%');
}
if ($request->get('categories')) {
$q->where('products.category_id', getCategoryIdFromSlug($request->get('categories')));
}
if ($request->get('sections')) {
$q->where('products.section_category_id', getSectionIdFromSlug($request->get('sections')));
}
if ((App::getLocale()) == 'en') {
// $q->orderBy('product_name_lang->en');
} else {
// $q->orderBy('product_name_lang->fr');
}
if ($request->get_j0_product == true) {
$q->where('products.delivery', 'J0');
}
// $q->orderBy('sale_price', 'DESC');
// $q->orderBy('created_at', 'DESC');
// $q = $q->leftJoin('product_sort_order', function ($join) {
// $join->on('products.id', '=', 'product_sort_order.product_id');
// $join->on('products.sub_category_id', '=', 'product_sort_order.type_id');
// })->orderBy('product_sort_order.sort_order', 'ASC');
}
])->first();
model relationship inside category
public function subproducts(){
return $this->hasMany(Product::class,'sub_category_id','id');
}

How to add an additional condition in left join using query builder using Laravel

I have this Eloquent Query Builder in Laravel-5.8:
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$employeeCode = Auth::user()->employee_code;
$employeeemptypeid = HrEmployee::where('employee_code', $employeeCode)
->where('company_id', $userCompany)
->pluck('employee_type_id')->first();
$employeeegendercode = HrEmployee::where('employee_code', $employeeCode)
->where('company_id', $userCompany)
->pluck('gender_code')->first();
$leaveBalance = DB::table('hr_leave_types AS lt')
->leftJoin('hr_leave_type_details AS ltd', function($join) use ($userCompany) {
$join->on('ltd.leave_type_id', '=', 'lt.id')
->where('ltd.company_id', '=', $userCompany)
->where('ltd.employee_type_id', '=', $employeeemptypeid);
})
->leftJoin('hr_leave_requests AS lr', function($join) use ($userCompany, $userEmployee) {
$join->on('lr.leave_type_id', '=', 'lt.id')
->where('lr.company_id', '=', $userCompany)
->where('lr.employee_id', '=', $userEmployee)
->whereYear('lr.commencement_date', '=', date('Y'))
->where('lr.leave_status', 4);
})
->leftJoin('hr_employees AS e', function($join) use ($userCompany, $userEmployee) {
$join->on('e.id', '=', 'lr.employee_id')
->where('e.company_id', '=', $userCompany)
->where('e.id', '=', $userEmployee)
->where('e.employee_type_id', '=', 'ltd.employee_type_id');
})
->where('lt.company_id', '=', $userCompany)
->select(
'lt.leave_type_name as leaveCategory',
'ltd.no_of_days as applicableLeave',
DB::raw("IFNULL(SUM(lr.no_of_days),0) as approvedLeave")
)
->groupBy('lt.leave_type_name', 'e.id')
->get();
This is used to get the Employee Leave Balance. It was working fine till this point.
But there are some leave types that belong to only male, only female and some to both genders.
How do I add this to the query above:
if($employeeegendercode == 0)
{
$leavetypes = HrLeaveType::join('hr_leave_type_details', 'hr_leave_type_details.leave_type_id', '=', 'hr_leave_types.id')
->select('hr_leave_types.id as id', 'hr_leave_types.leave_type_name')
->where('hr_leave_types.company_id', $userCompany)
->where('hr_leave_type_details.employee_type_id', $employeeemptypeid)
->whereIn('hr_leave_type_details.leave_applicable_gender', [1, 3])
->get();
}else{
$leavetypes = HrLeaveType::join('hr_leave_type_details', 'hr_leave_type_details.leave_type_id', '=', 'hr_leave_types.id')
->select('hr_leave_types.id as id', 'hr_leave_types.leave_type_name')
->where('hr_leave_types.company_id', $userCompany)
->where('hr_leave_type_details.employee_type_id', $employeeemptypeid)
->whereIn('hr_leave_type_details.leave_applicable_gender', [1, 2])
->get();
}
especially for:
hr_leave_type_details.leave_applicable_gender', [1, 3]
and
hr_leave_type_details.leave_applicable_gender', [1, 2]
Thanks
You could use the when() query builder function.
/**
* Apply the callback's query changes if the given "value" is true.
*
* #param mixed $value
* #param callable $callback
* #param callable|null $default
* #return mixed|$this
*/
public function when($value, $callback, $default = null)
{
if ($value) {
return $callback($this, $value) ?: $this;
} elseif ($default) {
return $default($this, $value) ?: $this;
}
return $this;
}
Here are a couple of example from the docs:
// If $request->input('role') is truthy (in this context, it's not null),
// then filter users using $role variable.
$role = $request->input('role');
$users = DB::table('users')
->when($role, function ($query, $role) {
return $query->where('role_id', $role);
})
->get();
// If $sortBy isn't null, order by $sortBy
// if $sortBy is null, order by 'name'
$sortBy = null;
$users = DB::table('users')
->when($sortBy, function ($query, $sortBy) {
return $query->orderBy($sortBy);
}, function ($query) {
return $query->orderBy('name');
})
->get();
Applying this to your example, I guess you'd have the following:
$leavetypes = HrLeaveType::join('hr_leave_type_details', 'hr_leave_type_details.leave_type_id', '=', 'hr_leave_types.id')
->select('hr_leave_types.id as id', 'hr_leave_types.leave_type_name')
->where('hr_leave_types.company_id', $userCompany)
->where('hr_leave_type_details.employee_type_id', $employeeemptypeid)
->when(
$employeeegendercode == 0,
function ($query) {
return $query->whereIn('hr_leave_type_details.leave_applicable_gender', [1, 3]);
},
function ($query) {
return $query->whereIn('hr_leave_type_details.leave_applicable_gender', [1, 2]);
}
)
->get();
I exagerated the indentation a bit to make it clear. For relatively small changes like this you could use PHP 7.4's shorthand closures.
->when(
$employeeegendercode == 0,
fn ($query) => $query->whereIn('hr_leave_type_details.leave_applicable_gender', [1, 3]),
fn ($query) => $query->whereIn('hr_leave_type_details.leave_applicable_gender', [1, 2])
)
More on the subject
https://laravel.com/docs/5.8/queries#conditional-clauses

How to declare the result from another function in Laravel

The first 2 functions are for the dropdown, and the last function filter function is to fetch the data into datatable. I want to use the results from function FirstName ($FirstName= [];) and LastName ($LastName= [];) for this purpose.
public function FirstName(Request $request)
{
$FirstName= [];
if($request->has('q')){
$search = $request->q;
$FirstName= DB::table("user")
->select("id","First_Name")
->where('First_Name','LIKE',"%$search%")
->get();
}
return response()->json($FirstName);
}
public function LastName(Request $request)
{
$LastName= [];
if($request->has('q')){
$search = $request->q;
$LastName= DB::table("user")
->select("id","Last_Name")
->where('Last_Name','LIKE',"%$search%")
->get();
}
return response()->json($Last_Name);
}
public function filter()
{
if(!empty($FirstName)) //catch from other function
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln')
->where('First_Name', $FirstName)
->where('Last_Name', $LastName)
->get();
}
else
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln')
->get();
}
return datatables()->of($data)->make(true);
$data = DB::table('user')
->select('Last_Name','First_Name')
->groupBy('First_Name')
->groupBy('Last_Name')
->orderBy('First_Name', 'ASC')
->orderBy('Last_Name', 'ASC')
->get();
return response()->json($data);
}
What I did above is put the array from function first and last name to the filter function. But i got it wrong. What should be done to fix this?

How can i check request comes or not in laravel?

I want to get $data['student'] if request get (like: student-guardian?reg_no=0001 in URL).
if no any parameter on url $data['student'] don't needed.
My StudentGuardian function Like:
public function studentGuardian(Request $request)
{
$data = [];
if(!empty($request)){
$data['student'] = Student::select('id','reg_no','reg_date', 'first_name', 'middle_name', 'last_name','faculty', 'semester','status')
->where(function ($query) use ($request) {
if ($request->has('reg_no')) {
$query->where('students.reg_no', 'like', '%'.$request->reg_no.'%');
$this->filter_query['students.reg_no'] = $request->reg_no;
}
})
->get();
}
return view(('studentguardian.index'), compact('data'));
}
This is what you need:
public function studentGuardian(Request $request)
{
$data = [];
// check request has any parameter
if($request->all()){
// query and get list student
$data['student'] = Student::select('id','reg_no','reg_date', 'first_name', 'middle_name', 'last_name','faculty', 'semester','status')
->where(function ($query) use ($request) {
if ($request->has('reg_no')) {
$query->where('students.reg_no', 'like', '%'.$request->reg_no.'%');
$this->filter_query['students.reg_no'] = $request->reg_no;
}
})
->get();
} else {
//do something else
}
// return data to view
return view('studentguardian.index', compact('data'));
}
First, your if(!empty($request)) is useless, $request is always a Request object, not empty.
Second, you can use just if($request->all()) { ... } to check if request array is empty.

Resources