I can't add string to all value an array - laravel

I am new in developing ِAPi from laravel i need to insert path app into value an array
$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 = 'http://127.0.0.1:8000/Imaga_halls/'.$array;
}
array_push($results, $hall);
}
return response()->json($results);
}
the error is
ErrorException: Array to string conversion

$hall->image_path = 'http://127.0.0.1:8000/Imaga_halls/'.$array;
You are trying to concat an array to a string here.

After get() method on query builder, you will get the collection, so that you can use map() function to loop every hall object.
And concat prefix path with image:
$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 = $halls->map(function($hall) {
$array = json_decode($hall->image_path, true);
$hall->image_path = collect($array)->map(function($image) {
return 'http://127.0.0.1:8000/Imaga_halls/'.$image;
})->toArray();
return $hall;
});
return response()->json($results);

Related

Laravel 9.5.1 Undefined Variable on return view

Good day, I'm having a problem on passing data from controller to the blade.
This is the code from controller:
function dashboard(){
$adminData = ['LoggedAdminInfo'=>Admin::where('id','=',session('LoggedAdmin'))->first()];
$sensor_latest_data = array('list'=>DB::table('sensors')->latest('id')->first());
$sensor_data = Sensor::select('id', 'created_at')->get()->groupBy(function($data) {
return Carbon::parse($data->created_at)->format('M');
});
return view('admin.index', $adminData, $sensor_latest_data, ['chart_data'=>$sensor_data]);
}
The other data is working fine except for the last argument on return view.
I tried putting it inside the compact() function and it returned this:
return view('admin.index', $adminData, $sensor_latest_data, compact(['chart_data'=>$sensor_data]));
Compact function gets the variable name from string and map it to an array. For exmaple if you use compact('test'), it will search for test variable and map it and return it as ['test' => $test]
return view('admin.index', ['adminData' => $adminData, 'sensor_latest_data' => $sensor_latest_data, 'chart_data'=>$sensor_data]);
or just change your function to :
function dashboard(){
$adminData = ['LoggedAdminInfo'=>Admin::where('id','=',session('LoggedAdmin'))->first()];
$sensor_latest_data = array('list'=>DB::table('sensors')->latest('id')->first());
$chart_data = Sensor::select('id', 'created_at')->get()->groupBy(function($data) {
return Carbon::parse($data->created_at)->format('M');
});
return view('admin.index', compact('adminData', 'sensor_latest_data', 'chart_data'));
}
and here is simplified version:
function dashboard(){
$LoggedAdminInfo = Admin::where('id','=',session('LoggedAdmin'))->first();
$list = DB::table('sensors')->latest('id')->first();
$chart_data = Sensor::select('id', 'created_at')->get()->groupBy(function($data) {
return Carbon::parse($data->created_at)->format('M');
});
return view('admin.index', compact('LoggedAdminInfo', 'list', 'chart_data'));
}

laravel 6 - how to add new object in get all records

Postman return response
I need to add an array field after "transaction_type": null, "repay": true
if "payment_status": payment_pending
loop on $getAllOrders
$outputOrders = [];
foreach ($getAllOrders as $order){
$order['repay'] = $order['payment_status']=="payment_pending";
$outputOrders = $order;
}
then you can return the array $outputOrders instead of getAllOrders

Laravel query to output json data as select list. How to amend existing code to concatenate two values

I've got a pre-existing function in my controller that will run a simple query and return the model_name and id then return the result as json.
public function getModel($id)
{
$models = DB::table('model')->where('man_id',$id)->pluck('model_name','id');
return json_encode($models);
}
New requirement is that I include an additional column named model_num with the query. Plan is to concatenate the model_name and model_num columns.
Tried the following, but it doesn't return any values and I get a 404 response for the json:
public function getModel($id)
{
$models = DB::table("model")->select("id","CONCAT(model_name, '-', model_num) as model")->where("man_id",$id)->pluck('model','id');
return json_encode($models);
}
Am I missing something obvious?
You are using SQL functions within a select these will probably not work. You can use selectRaw instead:
public function getModel($id)
{
$models = DB::table("model")
->selectRaw("id, CONCAT(model_name, '-', model_num) as model")
->where("man_id",$id)
->pluck('model','id');
return response()->json($models); // response()->json() is preferable
}
alternatively you can do the concatenating in the PHP side:
public function getModel($id)
{
$models = DB::table("model")
->select("id", "model_name" "model_num")
->where("man_id",$id)
->get()
->mapWithKeys(function ($model) {
return [ $model->id => $model->model_name.'-'.$model->model_num ];
})
return response()->json($models);
}
public function getModel($id)
{
$models = DB::table('model')->where('man_id',$id)->first() ;
$models->model = $models->model_name. '-'. $models->model_num;
return json_encode($models->pluck('model', 'id');
}

Laravel Eloquent : Getting object instead of array

Trying to get a hotel in detail for hotel management API, in which for some hotels, getting
$hotel->rooms
as object and for some as array. The eloquent query in Hotel model as below.
public function detail($hotelid) {
return $this->with(['rooms','roomType'])->find($hotelid);
}
public function rooms() {
return $this->hasMany(HotelRooms::class, 'hotels_id')->where('status','active');
}
HotelRoom Model
public function roomType(){
return $this->hasOne(RoomType::class,'id','room_type_id')->where('status','active');
}
Controller
public function __construct(){
$this->model = new Hotel();
}
public function hotelDetail(Request $request){
$data = $this->model->detail($request->input('hotel_id'));
foreach($data->rooms as $key=>$room){
if(!$room->roomType){
unset($data->rooms[$key]);
continue;
}
}
return response()->json([
'status' => true,
'status_message' => 'successful',
'data' => $data,
]);
}
response
{
"id":"id",
"name":"name",
"rooms":{
"1":{},
"2":{}
}
}
{
"id":"id",
"name":"name",
"rooms":[
{},
{},
]
}
When you use unset on array, your array indexes remain for each item. Same as for collection->filter() or for array_filter() that is actually used in collection->filter(). That is why you need to rebuild the indexes:
$data->rooms = array_values($data->rooms->toArray());
to reindex the array.
Or use the foreach, but push values to new array:
$filteredRooms = [];
foreach($data->rooms as $key=>$room){
if(!$room->roomType){
continue;
}
$filteredRooms[] = $room;
}
$data->rooms = $filteredRooms;
Or instead of foreach loop, use filter for collection in combination with values() :
$filteredRooms = $data->rooms->filter(function ($room, $key) {
return (!$room->roomType)? false : true;
})->values();
After filtering array you have to re-index your array.
foreach($data->rooms as $key=>$room){
if(!$room->roomType){
unset($data->rooms[$key]);
continue;
}
}
$data->rooms = $data->rooms->values();

Laravel 5.4 Return as array not object

The following method is intended to return an array with another array, 'data' and an Object (The result of some eloquent query).
It is however returning an array with two objects in it; $data is somehow being converted to an object with multiple child-objects, rather than being an array of objects. It should be noted that a dd($data) before the return statement reveals that it is indeed an array of objects. I think that somehow the Laravel middleware that handles response is returning this as an object instead...
Any idea how to work around this?
public function getTestData($id) {
$participants = Participant::where('test_id', $id)->with('testRecords')->get();
$finalRecordValue = TestRecord::where('test_id', $id)->orderBy('created_at', 'desc')->first();
$data = [];
foreach ($participants as $participant) {
foreach ($participant->testRecords as $testRecord) {
if (!array_key_exists((int)$testRecord->capture_timestamp, $data)) {
$data[$testRecord->capture_timestamp] = (object)[
'category' => $testRecord->capture_timestamp,
'value' . "_" . $participant->id => $testRecord->score
];
} else {
$data[$testRecord->capture_timestamp]->{"value" . "_" . $participant->id} = $testRecord->score;
}
}
}
return [$data, Auth::user()->tests()->findOrFail($id)];
}
Try this before excuting return sentence or in it:
array_values($data);

Resources