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
Related
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);
}
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.
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"]" }]
}
I am working on a laravel webservice, my code is the following
public function getLanguageshow(){
$user_id=$_REQUEST['user_id'];
$profiles="SELECT * FROM `abserve_language_details` as `le` where `le`.`user_id`=".$user_id;
$details=\DB::SELECT($profiles);
$prof = \DB::table('abserve_proficiency')->select('*')->get();
$vals = explode(',', $details[0]->lan_proficiency);
foreach ($prof as $key => $value) {
if(in_array($value->id, $vals))
$lang_prof[] = $value->name;
}
$lang_prof = implode(',', $lang_prof);
foreach ($details as $key => $value) {
$value->lang_prof = $lang_prof;
}
$response['language_details'] = $details;
echo json_encode($response);exit;
}
and my result is
{
"language_details":[
{
"id":12,
"user_id":121,
"languages":"Tamil,English,Chinese,Bulgarian,Amharic,Fiji",
"lan_proficiency":"1,5,4,3,2,4",
"read":"1,1,1,1,1,1",
"write":"1,1,1,1,1,1",
"speak":"1,1,1,1,1,1",
"lang_prof":"elementary,limited_working,professional_working,full_professional,native_or_bilingual"
}
]
}
In this result lan_proficiency have 6 ids (1,5,4,3,2,4) but that id name ("lang_prof":"elementary,limited_working,professional_working,full_professional,native_or_bilingual") displays 5 names only 4 is repeated
I want result
{
"language_details":[
{
"id":12,
"user_id":121,
"languages":"Tamil,English,Chinese,Bulgarian,Amharic,Fiji",
"lan_proficiency":"1,5,4,3,2,4",
"read":"1,1,1,1,1,1",
"write":"1,1,1,1,1,1",
"speak":"1,1,1,1,1,1",
"lang_prof":"elementary,limited_working,professional_working,full_professional,native_or_bilingual,full_professional"
}
]
}
I'm busy with a tutorial and I ended up getting an error that says
This webpage has a redirect loop
I know that the problem is here in my routes.php
Route::group(["before" => "guest"], function(){
$resources = Resource::where("secure", false)->get();
foreach($resources as $resource){
Route::any($resource->pattern, [
"as" => $resource->name,
"uses" => $resource->target
]);
}
});
Route::group(["before" => "auth"], function(){
$resources = Resource::where("secure", true)->get();
foreach($resources as $resource){
Route::any($resource->pattern, [
"as" => $resource->name,
"uses" => $resource->target
]);
}
});
UserController
class UserController extends \BaseController {
public function login()
{
if($this->isPostRequest())
{
$validator = $this->getLoginValidator();
if($validator->passes())
{
$credentials = $this->getLoginCredentials();
if(Auth::attempt($credentials)){
return Redirect::route("user/profile");
}
return Redirect::back()->withErrors([
"password" => ["Credentials invalid."]
]);
}else{
return Redirect::back()
->withInput()
->withErrors($validator);
}
}
return View::make("user/login");
}
protected function isPostRequest()
{
return Input::server("REQUEST_METHOD") == "POST";
}
protected function getLoginValidator()
{
return Validator::make(Input::all(), [
"username" => "required",
"password" => "required"
]);
}
protected function getLoginCredentials()
{
return [
"username" => Input::get("username"),
"password" => Input::get("password")
];
}
public function profile()
{
return View::make("user/profile");
}
public function request()
{
if($this->isPostRequest()){
$response = $this->getPasswordRemindResponse();
if($this->isInvalidUser($response)){
return Redirect::back()
->withInput()
->with("error", Lang::get($response));
}
return Redirect::back()
->with("status", Lang::get($response));
}
return View::make("user/request");
}
protected function getPasswordRemindResponse()
{
return Password::remind(Input::only("email"));
}
protected function isInvalidUser($response)
{
return $response === Password::INVALID_USER;
}
public function reset($token)
{
if($this->isPostRequest()){
$credentials = Input::only(
"email",
"password",
"password_confirmation"
) + compact("token");
$response = $this->resetPassword($credentials);
if($response === Password::PASSWORD_RESET){
return Redirect::route("user/profile");
}
return Redirect::back()
->withInput()
->with("error", Lang::get($response));
}
return View::make("user/reset", compact("token"));
}
protected function resetPassword($credentials)
{
return Password::reset($credentials, function($user, $pass){
$user->password = Hash::make($pass);
$user->save();
});
}
public function logout()
{
Auth::logout();
return Redirect::route("user/login");
}
}
GroupController
class GroupController extends \BaseController {
public function indexAction()
{
return View::make("group/index", [
"groups" => Group::all()
]);
}
public function addAction()
{
$form = new GroupForm();
if($form->isPosted()){
if($form->isValidForAdd()){
Group::create([
"name" => Input::get("name")
]);
return Redirect::route("group/index");
}
return Redirect::route("group/add")->withInput([
"name" => Input::get("name"),
"errors" => $form->getErrors()
]);
}
return View::make("group/add", [
"form" => $form
]);
}
public function editAction()
{
$form = new GroupForm();
$group = Group::findOrFail(Input::get("id"));
$url = URL::full();
if($form->isPosted()){
if($form->isValidForEdit()){
$group->name = Input::get("name");
$group->save();
$group->users()->sync(Input::get("user_id", []));
$group->resources()->sync(Input::get("resource_id", []));
return Redirect::route("group/index");
}
return Redirect::to($url)->withInput([
"name" => Input::get("name"),
"errors" => $form->getErrors(),
"url" => $url
]);
}
return View::make("group/edit", [
"form" => $form,
"group" => $group,
"users" => User::all(),
"resources" => Resource::where("secure", true)->get()
]);
}
public function deleteAction()
{
$form = new GroupForm();
if($form->isValidForDelete()){
$group = Group::findOrFail(Input::get("id"));
$group->delete();
}
return Redirect::route("group/index");
}
}
but I'm not sure how to go about fixing it especially since I was following a tutorial.