get first value from array column database - laravel

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"]" }]
}

Related

Laravel Query Builder Return Results

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;
}

Trying to get property 'point' of non-object

I have a problem with get value of object ,I tried many posts here in stackoverflow like this : Trying to get property of non-object - Laravel 5 but it isn't solved.
I have this controller method :
public function user_team($id)
{
$week = Week::where('status','active')->first();
$week_id = $week->id;
$team = Team::where('user_id',$id)->with('userteams')->get();
foreach ($team[0]->userteams as $userteam) {
$userteam->surname = $userteam->Club->surname;
$userteam->price = $userteam->Club->price;
$points = Userpoint::where('club_id',$userteam->club_id)->where('week_id',$week_id)->where('user_id',$id)->first();
$point = $points->point;
$userteam->point = $point;
unset($userteam->Club);
}
return $team;
}
teams return this in post man :
[
{
"id": 40,
"team_name": "",
"season_id": 1,
"week_id": 2,
"user_id": 223269719,
"created_at": "2021-07-30T13:34:44.000000Z",
"updated_at": "2021-07-30T13:34:44.000000Z",
"userteams": [
{
"id": 277,
"team_id": 40,
"club_id": 1,
"created_at": "2021-07-30T13:34:44.000000Z",
"updated_at": "2021-07-30T13:34:44.000000Z"
},
{
"id": 278,
"team_id": 40,
"club_id": 21,
"created_at": "2021-07-30T13:34:44.000000Z",
"updated_at": "2021-08-01T10:37:03.000000Z"
},
and $points->point is return a value : 9
but when I try
$point = $points->point
it give me error : Trying to get property 'point' of non-object
foreach ($team[0]->userteams as $key => $userteam) {
$userteam->surname = $userteam->Club->surname;
$userteam->price = $userteam->Club->price;
$points = Userpoint::where('club_id',$userteam->club_id)->where('week_id',$week_id)->where('user_id',$id)->first();
$team[0]->userteams[$key]['point'] = $points->point;
unset($userteam->Club);
}
There i updated it, can you try again with this code
I solved it :
public function user_team($id)
{
$week = Week::where('status','active')->first();
$week_id = $week->id;
$team = Team::where('user_id',$id)->with('userteams')->first();
foreach ($team->userteams as $userteam) {
$userteam->surname = $userteam->Club->surname;
$userteam->price = $userteam->Club->price;
$points = $userteam->Club->userpoints;
if(isset($oiints)){
foreach ($points as $point) {
if($point->user_id == $id){
$userteam->point = $point->point;
}
}
}else{
$userteam->point = 0;
}
unset($userteam->Club->userpoints);
unset($userteam->Club);
}
return $team;
}

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.

How to respond data with an array instead of object

I want to receive an array for data, something like this:
"data": [
"6": {
"title": "..",
"photo": ..
}
]
But I am receving an object :
"data": {
"6": {
"title": "..",
"photo": ".."
}
}
And another intresting fact is that for first page I am receiving how it is needed:
"data": [
"1": {
"title": "..",
"photo": ..
},
.
.
.
"6": {
"title": "..",
"photo": ..
}
]
This is my function in controller:
$lists = [];
$cooks = cook::all();
foreach ($cooks as $cook) {
$list = [
'title' => $cook->title,
'photo' => $cook->photos->path,
'recipe' => $cook->recipe->description
];
$lists[] = $list;
}
$collection = $this->paginate($lists, $perPage = 6, $page = null, $options = []);
return new mainCollection($collection);
I have the following function for pagination:
public function paginate($items, $perPage = 15, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
and the following is my resourceColection(mainColection) :
public function toArray($request)
{
return [
'data' => $this->collection,
'meta' => ['pagination' => $this->pagination]
];
}
You can use laravel map since you're working with collections.
$array = $this->collection->map(function ($item, $key) {
return [
'title': "tort",
...
]
});
and encode it as json
public function toArray($request)
{
return [
'data' => json_encode($array),
'meta' => ['pagination' => $this->pagination]
];
}
also you read the documentation here: https://laravel.com/docs/5.8/collections

Laravel one to one relationships and query

I have customers who have been classified as (individual - company), I want to get all customer information from the main table and subtable into one query, I tried many times and I did not find a solution to that .. My attempts at the end of this topic
My tables:
customer_type
id
type
customers
id
address
customer_type_id
customer_individual
id
first_name
last_name
customer_id
customer_company
id
company_name
logo
customer_id
My RelationShips:
CustomerType.php
class CustomerType extends Model
{
public function customers()
{
return $this->hasMany('App\Customer');
}
}
Customer.php
class Customer extends Model
{
public function customer_type()
{
return $this->belongsTo('App\CustomerType');
}
public function more()
{
$related = ($this->customer_type_id == '1') ?
'App\CustomerIndividual' : 'App\CustomerCompany';
// 1 => individual
return $this->hasOne($related, 'customer_id');
}
}
CustomerIndividual.php
class CustomerIndividual extends Model
{
public function customer()
{
return $this->belongsTo('App\Customer');
}
}
CustomerCompany.php
class CustomerCompany extends Model
{
public function customer()
{
return $this->belongsTo('App\Customer');
}
}
I want the output as follows:
[
{
"id": 1,
"customer_type_id": 1,
"address": "New York",
"more": {
"id": 1,
"customer_id": 1,
"first_name": "John",
"last_name": "doe"
}
},
{
"id": 2,
"customer_type_id": 2,
"address": "london",
"more": {
"id": 2,
"customer_id": 2,
"name": "ANA IT Company",
"logo": "analogo.png"
}
}
]
These are my attempts:
return Customer::with(['person', 'company'])->get();
$customers = Customer::query();
$customers->when($customers->customer_type_id === 1, function($q){
return $q->with('person');
});
$customers->when($customers->customer_type_id === 2, function($q){
return $q->with('company');
});
$c = $customers->get();
return $c;
I hope to find a solution here.
What you could do is to create a new collection and add them to that.
Assuming that $q->with('person') is an object:
$collection = new \Illuminate\Database\Eloquent\Collection;
$customers->when($customers->customer_type_id === 1, function($q){
$collection->push($q->with('person'));
});
$customers->when($customers->customer_type_id === 2, function($q){
$collection->push($q->with('company'));
});
$c = $collection->flatten();
return $c;
Docs: Here

Resources