Laravel Query Builder Return Results - laravel

I have below Laravel Query, which runs very fine and returns the desired results.
$email = (Auth::user()->email);
$UerType = DB::table('tbl_schools')->where('email', $email)->pluck('type');
$parent_ids = DB::table('tbl_schools')->where('email', $email)->pluck('id');
// return $parent_ids;
if ($UerType == 'sub_admin') {
$children = DB::table('tbl_schools')->whereIn('id', $parent_ids)->get();
return $children;
} elseif ($UerType == 'school') {
$children = DB::table('tbl_schools')->where('email', $email)->get();
return $children;
} elseif ($UerType = 'admin') {
$children = DB::table('tbl_schools')->where('email', $email)->get();
return $children;
}
Out from Above is as expected
{
"id": 15,
"type": "sub_admin",
"parent_id": "12",
"username": "",
"access_role_type": "SCH2486518",
"school_code": "SCH2486518",
"school_name": "Test School",
"school_ad_name": "Support",
"address": "",
"email": "someemail#mail.com",
"mobile": "+2332123123123",
"school_logo": "",
"profile_image": "",
"status": "active",
"created": "2020-09-28 16:41:44",
"updated": "0000-00-00 00:00:00",
"token": ""
}
Now I need to Pick specific fields and save them to session for future use, but when I run the below code, strangely I still get the entire Query Result which is strange.
$email = (Auth::user()->email);
$UerType = DB::table('tbl_schools')->where('email', $email)->pluck('type');
$parent_ids = DB::table('tbl_schools')->where('email', $email)->pluck('id');
// return $parent_ids;
if ($UerType == 'sub_admin') {
$children = DB::table('tbl_schools')
->select('id','type','parent_id','school_name')
->whereIn('id', $parent_ids)
->get();
return $children;
} elseif ($UerType == 'school') {
$children = DB::table('tbl_schools')
->Select('id','type','parent_id','school_name')
->where('email', $email)
->get();
return $children;
} else {
$children = DB::table('tbl_schools')
->Select('id','type','parent_id','school_name')
->where('email', $email)
->get();
return $children;
}
I need help

First of all, you don't need to call the same query two times. Next, you are returning an array and compare it with a string. Do the following way. Hope this will give you the exact result.
$email = (Auth::user()->email);
$user = DB::table('tbl_schools')->where('email', $email)->first();
if ($uerType->type == 'sub_admin') {
$children = DB::table('tbl_schools')->whereIn('id', $user->id)->get();
return $children;
} elseif ($user->type == 'school') {
$children = DB::table('tbl_schools')->where('email', $email)->get();
return $children;
} elseif ($user->type = 'admin') {
$children = DB::table('tbl_schools')->where('email', $email)->get();
return $children;
}

Related

Loop through a string array in laravel

I'm trying to loop through a a string and get array of records where the service status is equals to complete or cancelled. I'm having an issue of get all the records instead it response with the last record from the list.
My Controller:
$id = $request->user_id;
$history = bookings::select('*')->whereIn('service_status', ['complete', 'cancelled'])->where(['specialist_id'=>$id])->orderBy('time', 'DESC')->get();
if($history->isempty()){
return response()->json(['statusCode'=>'5', 'statusMessage' => 'Empty Record', 'data' =>[]]);
}else{
for($i = 0; $i < count($history); $i++){
$b_id = $history[$i]->id;
$service = $history[$i]->service;
$time = $history[$i]->time;
$date = $history[$i]->date;
$location = $history[$i]->location;
$payment = $history[$i]->payment_type;
$price = $history[$i]->amount;
$special_request = $history[$i]->special_request;
$s_id = $history[$i]->costumer_id;
}
$user = User::with('profile')->find($s_id);
$data = array(['id'=>$b_id, 'date'=>$date, 'name'=>$user->name." ".$user->profile->lastname, 'speccial_request'=>$special_request, 'item'=>$service, 'time'=>$time." - 1 hour", 'location'=>$location, 'total'=>"$price"]);
return response()->json(['statusCode'=>'0', 'statusMessage' => 'Successful','data' => $data], 200);
}
My response is as follows:
{
"statusCode": "0",
"statusMessage": "Successful",
"data": [
{
"id": 5,
"date": "2020-07-08",
"name": "User1",
"speccial_request": null,
"item": "Service",
"time": "10:00 - 1 hour",
"location": "street, city",
"total": "300"
}
]
}
I want to get all the items from the DB not just one.
You need to create an empty array ($data) and push to that array in each iteration.
Try below code:
$id = $request->user_id;
$history = bookings::select('*')->whereIn('service_status', ['complete', 'cancelled'])->where(['specialist_id'=>$id])->orderBy('time', 'DESC')->get();
if($history->isempty()){
return response()->json(['statusCode'=>'5', 'statusMessage' => 'Empty Record', 'data' =>[]]);
}else{
$data=[];
for($i = 0; $i < count($history); $i++){
$b_id = $history[$i]->id;
$service = $history[$i]->service;
$time = $history[$i]->time;
$date = $history[$i]->date;
$location = $history[$i]->location;
$payment = $history[$i]->payment_type;
$price = $history[$i]->amount;
$special_request = $history[$i]->special_request;
$s_id = $history[$i]->costumer_id;
$user = User::with('profile')->find($s_id);
array_push($data,['id'=>$b_id, 'date'=>$date, 'name'=>$user->name." ".$user->profile->lastname, 'speccial_request'=>$special_request, 'item'=>$service, 'time'=>$time." - 1 hour", 'location'=>$location, 'total'=>"$price"]);
}
return response()->json(['statusCode'=>'0', 'statusMessage' => 'Successful','data' => $data], 200);
}

insert path URL into values an array

i want to add the url image in value to array
public function show(){
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','halls.hall_adress','halls.hall_details','price_hours','price_int','halls.hall_name','imagas.image_path')->where('halls.id',157)
->get();
$results=[];
foreach ($halls as $hall) {
$array=json_decode($hall->image_path,true);
if (is_array($array))
{
$hall->image_path = $array;
}
array_push($results, $hall);
}
return response()->json($results);
}
output like this
{
"id": 157,
"hall_name": "ali",
"hall_adress": "st-50",
"hall_details": null,
"price_hours": "3000",
"price_int": "500",
"image_path": [
"1579635535.jpg",
"1579635536.jpg",
"1579635537.png",
"1579635538.png"
]
}
but i need pass string path url to array and show output like this
{
"id": 157,
"hall_name": "ali",
"hall_adress": "st-50",
"hall_details": null,
"price_hours": "3000",
"price_int": "500",
"image_path": [
"http://127.0.0.1:8000/images_ravs/1579635535.jpg",
"http://127.0.0.1:8000/images_ravs/1579635536.jpg",
"http://127.0.0.1:8000/images_ravs/1579635537.png",
"http://127.0.0.1:8000/images_ravs/1579635538.png"
]
}
Iterate through the image array and add the rest of the URL.
foreach ($halls as $hall) {
$array = json_decode($hall->image_path, true);
if (is_array($array)) {
foreach($array as $index => $image) {
$array[$index] = "http://127.0.0.1:8000/images_ravs/" . $image;
}
$hall->image_path = $array;
}
}
Hope this helps you.

get first value from array column database

I need to get the fist item an array from select database using loop for but when i do't my outfit display all the value for array
public function index() {
$hall=DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','imagas.image_path')
->get();
$results =[];
foreach ($hall as $halls ) {
$array=$halls->image_path ;
for ($i=0; $i<$array; $i++) {
$halls=$array[0];
}
array_push($results, $halls);
}
return response()->json($results);
}
JSON Output
[
{ "id": 159,
"hall_name": "asdad",
"image_path": "[\"1579635948.jpg\",\"1579635948.jpg\",\"1579635948.png\",\"1579635948.png\"]"
},
{
"id": 160,
"hall_name": "dsfdsf",
"image_path": "[\"1579636069.jpg\",\"1579636069.png\",\"1579636069.png\",\"1579636069.png\"]"
},
]
I want to display the first value from all image_pathlike this
[ {
"id": 160,
"hall_name": "dsfdsf",
"image_path": "["1579636069.jpg"]"
},
]
You may use decode your $hall->image_path string before loop through it
public function index() {
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','imagas.image_path')
->get();
$results =[];
foreach ($halls as $hall) {
$array = json_decode($hall->image_path, true);
if (is_array($array)) {
$hall->image_path = reset($array) ?? NULL;
array_push($results, $hall);
}
}
return response()->json($results);
}
If I understand you correctly, you want the whole collection data but with modified image_path column, so it contains only the first path, right?
Here is the code using map helper function to output the collection as you desire:
public function index() {
$hall=DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','imagas.image_path')
->get();
$results = $hall->map(function ($item, $key) {
is_array($item->image_path) ? [head($item->image_path)] : [$item->image_path];
return $item;
});
return response()->json($results);
// [ { "id": 159, "hall_name": "asdad", "image_path": "["1579635948.jpg"]" },
// { "id": 160, "hall_name": "dsfdsf", "image_path": "["1579636069.png"]" }]
}

Laravel search with multiple conditions

I am performing a search in table with multiple condition which can exist individually and in group. These are my codes for the process.
Controller Code
if(\Input::has('title','category_id','type','price_max','price_min','seller_type_id','division_id','district_id','upazila_id')) {
$data['products'] = Custom::getProducts(\Input::get('title'), \Input::get('category_id'), \Input::get('type'),\Input::get('price_max'),\Input::get('price_min'),\Input::get('seller_type_id'),\Input::get('division_id'),\Input::get('district_id'),\Input::get('upazila_id'));
} else {
$data['products'] = \DB::table('products')->where('is_active', '=', 1)->get();
}
return view('pages.posts.list')->with($data);
Custom::getProducts
public static function getProducts($title = NULL, $category_id = NULL, $type = 0, $price_max = NULL, $price_min = NULL, $seller_type_id = 0, $division_id = NULL, $district_id = NULL, $upazila_id = NULL) {
$products = DB::table('products')
->where(function($query) use ($title, $category_id, $type, $price_max, $price_min, $seller_type_id, $division_id, $district_id, $upazila_id) {
if ($title)
$query->where('title', 'like', $title);
if ($category_id)
$query->where('category_id', $category_id);
if ($type != 0)
$query->where('type', $type);
if ($price_max)
$query->where('price', '<=', $price_max);
if ($price_min)
$query->where('price', '>=', $price_min);
if ($seller_type_id != 0)
$query->where('seller_type_id', $seller_type_id);
if ($division_id)
$query->where('division_id', $division_id);
if ($district_id)
$query->where('district_id', $district_id);
if ($upazila_id)
$query->where('upazila_id', $upazila_id);
})
->where('is_active', '=', 1)->get();
return $products;
}
But it is not working as expected. What I am doing wrong?

laravel advanced wheres not working

my function with advanced wheres is not giving any syntax error but its not even working. Its displaying. i have written this function following this example http://laravel.com/docs/queries#advanced-wheres
public function getData($wheres1 = array(),$wheres2 = array(),$wheres3 = array(),$wheres4 = array(),$wheres5 = array(),$wheres6 = array(),$wheres7 = array())
{
$query = Listing::query();
$result = array();
$query = $query->where(function($q){
if(!empty($wheres1)){
$count=0;
foreach($wheres1 as $where){
if($count==0)
{ $q = $q->where($where['field'], $where['operator'], $where['value']);
$count++;
}
else
$q = $q->orWhere($where['field'], $where['operator'], $where['value']);
}
}
})->where(function($q){
if(!empty($wheres2)){
$count=0;
foreach($wheres2 as $where){
if($count==0)
{ $q = $q->where($where['field'], $where['operator'], $where['value']);
$count++;
}
else
$q = $q->orWhere($where['field'], $where['operator'], $where['value']);
}
}
})->where(function($q){
if(!empty($wheres3)){
$count=0;
foreach($wheres3 as $where){
if($count==0)
{ $q = $q->where($where['field'], $where['operator'], $where['value']);
$count++;
}
else
$q = $q->orWhere($where['field'], $where['operator'], $where['value']);
}
}
});
$result = $query->orderBy('id', 'desc')->paginate(3);
return $result;
}
You need to add use for each where
$query = $query->where(function($q) use ($wheres1) {
....
}
You may try this approach:
$query = Listing::query();
if(is_array($wheres1) && count($wheres1)) {
$first = array_shift($wheres1);
$query->where($first['field'], $first['operator'], $first['value']);
if(count($wheres1)) {
foreach($wheres1 as $where) {
$query->orWhere($wheres['field'], $wheres['operator'], $wheres['value']);
}
}
}
Now repeat the same process for rest of the wheres, for example ($wheres2):
if(is_array($wheres2) && count($wheres2)) {
$first = array_shift($wheres2);
$query->where($first['field'], $first['operator'], $first['value']);
if(count($wheres2)) {
foreach($wheres2 as $where) {
$query->orWhere($wheres['field'], $wheres['operator'], $wheres['value']);
}
}
}
At last:
return $query->orderBy('id', 'desc')->paginate(3);

Resources