laravel api without respond - laravel

I have a issue, after i eliminate cors policy on laravel i sending some json data to check respond. But nothing happens...
I sending request by axios using react.js, i sending json data collected from state.
and now i trying to collect that data by laravel, but that is hardest patch.
already try something like that:
$content='test';
return Response::$content;
or just echo 'test' but nothing comes...
My code is inside controller.
class testRequest extends Controller
{
public function show(Request $request)
{
//$data = $request->json()->all();
// $experience = $data->experience;
$content='test';
return Response::$content;
}
}
for now i expect to get respond like 'test' but after that i will need to send a link to file path for respond.

the Response::$content is just wrong... the :: operator is used to access static member functions or attributes of the Response class... you should do something like this:
return Response::json(['test' => $content]);
or
return response()->json(['test' => $content]);
in order to respond with a JSON document.

Related

How to log every GET And POST data in Codeigniter 4?

my web application is doing a lot of AJAX calls (GET and POST) to our CodeIgniter 4 backend. My current approach to debug the AJAX call is setting manual logging messages within every method. Too time-consuming.
Do you know if there is a better way to do that? Overwriting a CI class?
I am happy about every help.
For logging the request you have to create the "after filters".
First You Define the Class which implements FilterInterface.
class Logger implements FilterInterface
{
use ResponseTrait;
public function before(RequestInterface $request)
{
...
}
public function after(RequestInterface $request, ResponseInterface $response)
{
...
}
}
In the after method, you will need to store the response and then save it using log_message.
public function after(RequestInterface $request, ResponseInterface $response)
{
$response_service = \Config\Services::response();
log_message('info', '{message}', ['message' => $response_service->getJSON()]
}
Here, I have stored used the response service explicitly and then simply called the getJSON to store the JSON body of the request. You will need to modify this for your problem. Also, do note you don't need to call the response service explicitly. There was another thread that showed how you can save the response implicitly, so you might want to refer to that.
Once the filter is done, you need to register the alias for the routes as below :
public $aliases = ['logger' => \App\Filters\Logger::class];
Once done you can either implement on individual routes or global routes.
Below is how you can implement it on global routes:
public $globals = [
'before' => [
...
],
'after' => [
'logger',
],
];
References : https://codeigniter4.github.io/userguide/incoming/filters.html?highlight=filter
https://codeigniter4.github.io/userguide/incoming/request.html?highlight=request
https://codeigniter4.github.io/userguide/general/logging.html?highlight=log_message
Just use
echo $this->request->getPost("usersemail"); die();
for usersemail input field

Laravel Eloquent Resource Collection response

So I am trying to use a resource collection to return datatable json information. Before I used my collection I first did a proof of concept that looked like this:
public function index()
{
$clients = QueryBuilder::for(Client::class)
->allowedIncludes('accounts')
->get();
if (request()->ajax()) {
return DataTables::of($clients)->make(true);
}
return view('client.index', compact('clients'));
}
This worked perfectly and the json response looked like so:
{data: [{id: "4428", number: "492501", name: "Test Client", email: "test#test.com",…},…]
draw:1
input:{view: "datatable", draw: "1",…}
recordsFiltered:2
recordsTotal:2}
Then I updated my index call to use my resource collection that looks like this:
public function toArray($request)
{
switch ($request->view) {
case 'datatable':
self::withoutWrapping();
return DataTables::of($this->collection)->make(true);
}
return parent::toArray($request);
}
The response is now plopped in an "original" attribute and a bunch of other items are added to the response. I don't understand why. It looks like this:
*callback: null
*charset: null
*content: <The above response is in here as a string>
*encodingOptions: 0
*statusCode: 200
*statusText: "OK"
*version: "1.0"
exception: null
headers: {}
original: <The above response is in here as an object>
I can set my dataSrc on datatables to original.data and it works fine but where did all this extra stuff come from? I have used a few other resource collections and never had all this stuff added in.
Update: because everything i am looking for is in "original" the pagination breaks as well as most of the other datatable functionality. If I move this return back into the controller it works fine.
So, the answer has to do with response type. The eloquent resource has an undocumented function called "toResponse" and if your return is going to be some kind of jsonResponse you need to modify it instead of your toArray method. What was happening was I was returning a JsonResponse and it was turning it into an array and just returning that json encoded.
To be clear as mud, here is my new Resource:
public function toResponse($request)
{
switch ($request->view) {
case 'datatable':
self::withoutWrapping();
return DataTables::of($this->collection)->toJson();
}
return parent::toResponse($request);
}
So, to reiterate, if you are returning an array or something that conforms to an array correctly (which datatables jsonresponse does not) you override "toArray". If you are returning a jsonResponse you need to override "toResponse".
Another option is to have your code start in toArray but when you know your going to return a jsonResponse you call $this->toResponse($request). Option is yours.

How Redirect to Other Method in one Controller with Request in laravel?

in my case i have a route for get and set API.
if user want to get something i don't want to check Validation. but if his wants to set, i Want to Check Request input validation with Request file.
look:
class EventsController extends Controller
{
public function get(Request $request)
{
if( empty($request['data']) )
{
// Return Request.. is ok
}elseif( !empty($request['data']) && $request->has('data.id') )
{
// so User want to insert in database and I want to check
// Validation with Request file in the method
// How can i Do this?
call $this->store( // send Request to that for Validation )
}
}
public function store(ValidateInput $request)
{
// Insert into Database
}
}
Note: in the getMethod i don't want check validation but in store method i want!
1- i don't want to use other Route and i want do Both in one Request and Route
2- my main Question: who can i change Method in Controller and pass Request to that!
you can try something like :
//Calling a method that is from the EventsController
$result = (new EventsController)->store();
but the best approche is to split them into two methods as #Sandeesh said

laravel api with vue 2 js not returning data - could 'localhost:8000' (or '127.0.0.1:8000') be the issue?

I am using the repo https://github.com/mschwarzmueller/laravel-ng2-vue/tree/03-vue-frontend so I have 100% confidence in the reliability of the code. I can post through the laravel api endpoint through the very simple Vue client, and also through Postman. Through Postman I can retrieve the table data array, but not so in the client app. In POSTMAN:
localhost:8000/api/quotes
works just fine.
IN THE vue 2 js CLIENT APP:
methods: {
onGetQuotes() {
axios.get('http://localhost:8000/api/quotes')
.then(
response => {
this.quotes = (response.data.quotes);
}
)
.catch(
error => console.log(error)
);
}
returns nothing. returning the response to Console.log returns nothing. The Network/XHR tab shows the table data rows, but I am not sure what that means.
I know for sure that this code works for others with their unique api endpoints, which I assume may not use localhost or '127:0.0.1:1080.
Edit: in response to request for more info
public function getQuotes()
{
$quotes = Quote::all();
$response = [$quotes];
return response()->json($response, 200);
}
and the relevant route:
Route::get('/quotes', [
'uses' => 'QuoteController#getQuotes'
]);
Just to confirm: I am using verified github repo code in which the ONLY change is my api endpoint addressas mentioned in the first line of the body of this question. . Note that the Laravel back end is also derived from a related repo in Max's fine tutorial. The running code can be seen at
So I really don't think this is a coding error- but is it a configuration error due to me using local host??
EDIT: It WAS a coding error in the laravel controller as shown below
The reason your code isn't working if because you haven't provided a key for your $quotes in your controller but you're looking for it in your vue file (response.data.quotes).
[$quotes] is essentially [0 => $quotes] so when the json response comes through it be 0: [...] not quotes: [...].
To get this to work you just need to change:
$response = [$quotes];
to:
$response = ['quotes' => $quotes];
Furthermore, just an FYI, you don't need to provide the 200 in response->json() as it's the default and you can just return an array and Laravel automatically return the correct json response e.g.:
public function getQuotes()
{
$quotes = \App\Models\Artist::all();
return compact('quotes'); //<-- This is just another way of writting ['quotes' => $quotes]
}
Obviously, you don't have to if you don't want to.
Hope this helps!

Laravel AJAX validation: Return HTML instead of JSON

As it's stated in docs, if AJAX validation fails you get json response:
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
But I'd prefer partial view with flashed error which is default for non AJAX.
So is it possible to emulate non AJAX or turn off AJAX without rebuilding source or some other awkwardness?
BTW, culprit function is buildFailedValidationResponse.
I got into a similar problem these days and ended up overwriting a method as well.
Under Laravel 5.1.20, i had to copy method response from class Illuminate\Foundation\Http\FormRequest into class App\Http\Requests\Request, and just like your answer, changed
if ($this->ajax() || $this->wantsJson()) {
with
if ($this->wantsJson())) {
This is the complete method in App\Http\Requests\Request class
public function response(array $errors)
{
if (!$this->pjax() && ($this->ajax() || $this->wantsJson())) {
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
Managed to solve the problem with brute force. Just overwritten the trait method in AuthController. Bad feel about that.
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if (/*$request->ajax() ||*/ $request->wantsJson()) { return new JsonResponse($errors, 422);
}

Resources