Compile loop after data return - php

I went to build an API using Lumen. i tryed to get data with a condition,
it's successfully return my data. My code is:
$speeches = Speech::where('is_requested', 0)->where('is_Submited', 0)->take(25)->get();
return response()->json(['status'=> 'Success', 'data' => $speeches], 200);
But i went when it's return my data, some field will update automicatly.
$speeches = Speech::where('is_requested', 0)->where('is_Submited', 0)->take(25)->get();
// return response()->json(['status'=> 'Success', 'data' => $speeches], 200);
foreach($speeches as $speechreq){
$speechreq->update([
'user_id' => Auth::user()->id,
'is_requested' => 1,
]);
return response()->json(['status'=> 'Success', 'data' => $speechreq], 200);
it returns only one data with the update. but I need 25 data. If I write my code like
$speeches = Speech::where('is_requested', 0)->where('is_Submited', 0)->take(25)->get();
return response()->json(['status'=> 'Success', 'data' => $speeches], 200);
foreach($speeches as $speechreq){
$speechreq->update([
'user_id' => Auth::user()->id,
'is_requested' => 1,
]);
// return response()->json(['status'=> 'Success', 'data' => $speechreq], 200);
}
it returns me 25 data but foreach loop doesn't work. So can anyone help me, please...?

Return this line after foreach loop.
return response()->json(['status'=> 'Success', 'data' => $speeches], 200);

Related

response error REST API CI3 not display in Client

I'm having a problem getting errors from the Rest API I created with codeigniter 3, or rather using the library from "https://github.com/chriskacerguis/codeigniter-restserver".
This problem occurs when I POST data to server via API.
When I try to post the same data as the data in the database. it will issue an error message data already exists. with status 409.
but I didn't get the error in the client application that I made. only displays "Null"
https://localhost/server/api/room
public function index_post()
{
try {
$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['noroom'])) {
throw new Exception('Error: field not found, field must be named noroom');
return false;
}
$exists = $this->Roommodel->findRoomByNoroomAndHotel($input['noroom'], $input['hotel_code'])->num_rows();
if ($exists > 0) {
$message = [
'status' => 409,
'message' => 'Data already exists',
];
$this->response($message, REST_Controller::HTTP_CONFLICT);
} else {
$dataRoom = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
];
$insert = $this->Roommodel->save($dataRoom);
if ($insert) {
$data = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
'message' => 'Success created data'
];
$message = [
'status' => 200,
'message' => 'Success',
'data' => $data,
];
$this->response($message, REST_Controller::HTTP_OK);
} else {
$message = [
'status' => 400,
'message' => 'Bad Request'
];
$this->response($message, REST_Controller::HTTP_BAD_REQUEST);
}
}
} catch (Exception $e) {
$message = [
'status' => 500,
'message' => $e->getMessage()
];
$this->response($message, REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
}
}
below is my coding on the client side, and I try to do var_dum() the result is "Null" when there is an error.
when I tried insomia, I got the error message.
var $API = "";
function __construct()
{
parent::__construct();
$this->API = "http://localhost/server";
$this->load->library('session');
$this->load->library('curl');
$this->load->helper('form');
$this->load->helper('url');
}
public function create()
{
if ($this->input->is_ajax_request()) {
$data = [
'hotel_code' => $this->input->post('hotel_code'),
'noroom' => $this->input->post('noroom'),
'room_type' => $this->input->post('room_type'),
'room_area' => $this->input->post('room_area'),
'description' => $this->input->post('description'),
];
$response = json_decode($this->curl->simple_post($this->API . '/api/room', json_encode($data), array(CURLOPT_BUFFERSIZE => 10)), true);
var_dump($response); die();
echo json_encode($response);
} else {
show_404();
}
}
if the post data is successful, it will send the success message. and managed to get the message.
please help me to solve this problem

Property [id] does not exist on this collection instance?

I want to show from UserController how many products the User used and user information. I have created two Resources for it. SO I search him using $id Here is My UserController code
public function show($id)
{
//
$user = User::find($id);
if (is_null($user)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user->id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
And here is my UserProductResource
<?php
namespace App\Http\Resources;
use App\Http\Resources\ProductResource;
use Illuminate\Http\Resources\Json\JsonResource;
class UserProductResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'profile_img' => $this->profile_img,
'products' => ProductResource::make($this->products),
];
}
}
And The error is
My Route is:
Route::get('/show-product/{id}', [UserController::class, 'showProduct']);
Try this solution:
You have a error in this query
$products = Product::where('user_id', $user_id)->get();
because $user_id is an object of the User, not a single value.
Your Code:
public function show($id)
{
//
$user_id = User::find($id);
if (is_null($user_id)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user_id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
New Code:
public function show($id)
{
//
$user = User::find($id);
if (is_null($user)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
$products = Product::where('user_id', $user->id)->get();
return response()->json([
'data' => new UserProductResource($products),
'status' => 200
], 200);
}
find($id) returns an object so you cant pass object in where(). Replace your below line
$products = Product::where('user_id', $user_id)->get();
with this line
$products = Product::where('user_id', $user_id->id)->get();
it will work.
new UserProductResource($products)
Here Object of Products is passed in resource file and if we check fields in UserProductResource they look like fields existing in User model.
Will $products have any field or relation like products ?
$products is a collection so UserProductResource::collection() should be used.
Ideally you should make relationship between User and Product and do this
$user = User::with('products')->find($id);
if (is_null($user_id)) {
return response()->json([
'message' => 'User Not Found',
'status' => 404
], 404);
}
return response()->json([
'data' => new UserProductResource($user),
'status' => 200
], 200);
and as there can be multiple products in UserProductResource you can do this
'products' => ProductResource::collection($this->products),

Show form errors on error page with validation in Laravel

If the $request->SN is either invalid or empty, I get an error like the following.
Trying to get property of non-object
Ticket::create([
'user_id' => Laptop::where('SN', $request->SN)->first()->user_id,
'laptop_id' => Laptop::where('SN', $request->SN)->first()->id,
'title' => $request->title,
'body' => $request->body,
'laptop_ww' => $request->laptop_ww
]);
How can I display a custom error instead of this exception? By default, it goes to an error page with status 500.
public function save(Request $request)
{
try{
Ticket::create([
'user_id' => Laptop::where('SN', $request->SN)->first()->user_id,
'laptop_id' => Laptop::where('SN', $request->SN)->first()->id,
'title' => $request->title,
'body' => $request->body,
'laptop_ww' => $request->laptop_ww
return view(your_address, "successfully saved");
]);
}catch(Exception ex){
return view(your_address, "Custom error here");
}
}
Try below -
$laptop = Laptop::where('SN', $request->SN)->first();
if(null === $laptop){
throw new Exception('No laptop found with SN'.$request->SN);
}
if(null === $laptop->user_id){
throw new Exception('Laptop with SN:'.$request->SN.' does has any user'.);
}
Ticket::create([
'user_id' => $laptop->user_id,
'laptop_id' => $laptop->id,
'title' => $request->title,
'body' => $request->body,
'laptop_ww' => $request->laptop_ww
]);
You will save a query and also errors are handled.

How to set return array user into response laravel

<?php
foreach($users as $user) {
$user = User::create(array(
'user_id' => $user['user_id'],
'user_text' => "1",
'other_id' => $user['other_id']
));
}
return Response::json(['success' => true, 'message' => 'successfully', 'data' => $user], 201);
How can i send multiple created users into the response it does not allow me setting user into data key please guide even i tried to set return response inside the loop it does allow only only value to set.
foreach( $users as $user ) {
$send_user[] = User::create(array('user_id' => $user['user_id'], 'user_text' => "1", 'other_id' => $user['other_id']));
}
return Response::json([
'success' => true,
'message' => 'successfully',
'data' => $send_user
], 200);
return response()->json(['type'=>'success','data'=>$user], 200);

Laravel 5.1 Download PDF with Event

My initial controller code for Event is:
try {
$sales = $this->sales->create([
'customer_id' => $customer->id,
'sales_details' => json_encode($vData),
'total_price' => ((int)$data['q-rfh'] * (int)$data['p-rfh']) + ((int)$data['q-rfh-spro'] * (int)$data['p-rfh-spro']),
'created_by' => $user->username,
]);
\Event::fire('print.invoice', $sales);
return \Response::json([
'type' => 'success',
'message' => 'Success creating sales!',
]);
}
catch (\Exception $e) {
return \Response::json([
'type' => 'danger',
'message' => $e->getMessage(),
]);
}
I need to print the invoice using event because I need to return a response with ajax to let user know the sales has been successfully made.
The event code is as simple as this:
public function handle(SalesModel $sales) {
if ($sales) {
$data = [
'sales' => $sales,
];
$pdf = \PDF::loadView('invoice.sales', $data);
return $pdf->download('inv_' . Carbon::now() . '.pdf');
}
}
EventServiceProvider already listens to it:
protected $listen = [
'print.invoice' => [
'App\Events\InvoiceEventHandler',
],
];
Everything works fine, except that the PDF is not downloaded. I'm using https://github.com/barryvdh/laravel-dompdf for creating and downloading the PDF. Can someone tell me what's wrong?
I give you and idea. Create the pdf file and store it at your server temporally
// return an absolute url
$pdfFile = \PDF::create('inv_' . Carbon::now() . '.pdf');
Now in your json response add the pdf file url in order to download it once the response arrives at client:
return \Response::json([
'type' => 'success',
'message' => 'Success creating sales!',
'pdf' => pdfFile
]);
From javascript, at success() method you can call the pdf in other request

Categories