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

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

Related

change prop based on parameter

In my app (Laravel + InertiaJS + Vue3), I want to refresh some client-side JS variables based on a client-side parameter:
Client has a table of events, each one holding a button with its corresponding event_id.
When pressed, the server receives a request and performs some calculations (dynamically generates an external URL and some parameters). Nothing is persisted to the database.
Hopefully, the generated URL and the parameters are sent-back to the client, and the user is then redirected there (client-side) using a POST form (that is why I can not redirect directly from the server).
What is the best way to do that?
This is what I have so far:
// In my controller
...
public function __construct()
{
$this->generator = new URLGenerator();
}
public function generate(Event $event)
{
$url = $this->generator->getURL($event);
return redirect()->back();
}
// My controller
public function index()
{
return Inertia::render('Events', [
'events' => fn () => new EventResource(
auth()->user()->events
)
]);
}
I need to somehow inject the $url variable back to Vue.
Thanks in advance for any help.

How to catch get parameter and cast it to int in Laravel?

I have the following controller:
class CustomerController extends Controller
{
public function index(int $customerId = 0) : Renderable
{
dd($customerId);
...
And I'm requesting it by the following url http://localhost/customers?customerId=123. I would like to catch customerId as int. But It always gives 0 (default value the for method's signature). Ok, I can do something like:
$customerId = $request->input('customerId');
But the approach with getting parameter from the method's signature is more attractive for me.
I have seen this answer. It looks like very nice! But it does not work for my case. Why? Where is the mistake? Thank you for attention!
Update
Here I will show my routes definitions:
Auth::routes(['register' => false, 'reset' => false]);
Route::middleware('auth')->group(function () {
Route::resource('customers', 'CustomerController');
});
If you want to use the Resource Route you have to pass the customerID parameter like below. And also you have to use one of these methods: show, edit,update or destroy in your controller.
Route::resource('customers', 'CustomerController')->parameters([
'customers' => 'customerId'
]);
For more details: https://laravel.com/docs/5.7/controllers#resource-controllers
AFAIK Laravel doesn't inject parameters this way.
If such URI is really needed - you should manually inspect request input for your variables.
If you want to use controller as written, you should use route parameters (e.g. /customers/{id}) instead of parameters after ?.
By default resource controllers use index() for displaying all entities and show() for displaying only one entity.
If you use Eloquent, you can also inject Customer model, e.g.
public function index(Customer $customer) : Renderable
Customer will be automatically found by id and injected in controller method.

laravel api without respond

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.

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

Pass array to the command bus

I'm trying to understand how to use the laravel 5.0 command bus, but I am struggling to get it right, so I'm looking for help with a few questions:
I'd like to dispatch an array of memberIds to run through a loop inside the handle function of the command.
$members:
array:2 [
0 => "147"
1 => "148"
]
This array is sent like this:
$this->dispatch(new SendMail($members));
How do I access the array in the handle method of SendMail command? I haven't found many examples, but nearly all of them pass $command into the handler.
public function handle($command)
{
//this doesn't work
foreach($command->members as $memberId){
$contractor = Contractor::find($memberId);
}
Do I need to return anything from the handler in order to continue running the other logic inside of my original function?
Since your trying to inject your $members array to your job's constructor method, you need to handle it there.
Then you'll be able to use your array in the hanle method.
// in your job class
protected $members;
public function __construct($members)
{
$this->members = $members
}
public function handle ()
{
foreach ($this->members as $member) {
//your logic
}
}
And if you want to inject an Eloquent model to your job (instead of an array) remember that you can typehint directtly in the constructor and , using the SerializesModels trait Laravel will retrieve it for you. This is described in the documentation.

Resources