change prop based on parameter - laravel

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.

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

Sending different data from different method on same route - laravel 8

I am trying to get order data in order tab and profile details data in profile tab.
Is it possible to achieve ???
If Yes, then please tell me how ?
If No, then please tell me, laravel is the most advance framework of PHP, why we can't send multiple data from multiple methods in same View ?
Controller
public function GetOrders()
{
$gtord = DB::table('orders')->where('email',Session::get('email'))->get();
return view('/my-account')->with('gtord',$gtord);
}
public function ProfileEdit()
{
$data = DB::table('customers')->where('email',Session::get('email'))->first();
return view('/my-account')->with('data',$data);
}
Routes
Route::get('/my-account', 'App\Http\Controllers\CustomerController#ProfileEd');
Route::get('/my-account', 'App\Http\Controllers\CustomerController#GetOrders');
Thank you in advance
You can't have multiple routes with the same 'signature', ie method and url.
If you're just showing/hiding tabs using JS, what you can do is return the view with two variables, eg:
public function AccountView()
{
$data = DB::table('customers')->where('email',Session::get('email'))->first();
$gtord = DB::table('orders')->where('email',Session::get('email'))->get();
return view('/my-account')->with(['data' => $data, 'gtord' => $gtord]);
}
And then just use one route:
Route::get('/my-account', 'App\Http\Controllers\CustomerController#AccountView');
If the two tabs are different urls, or you're using Vue or similar you would have two distinct routes with different signatures.
First, you can't have 2 same routes with the same method. It's quite logical and necessary. Otherwise, the whole routing system would collapse.
On the other hand, you can have a function in the controller, and call the other functions to collect data.
// web.php
Route::get('/my-account', 'App\Http\Controllers\CustomerController#index');
// controller
public function index()
{
$orders = $this->getOrders();
$profile = $this->getProfiles();
return view('yourView', compact(['orders', 'profile']));
}
public function getOrders()
{
//
}
public function getProfiles()
{
//
}
BTW, it's a better practice to move custom function to models, services or traits, and keep only the functions of 7 verbs in the contoller.

laravel - how can I call a function stored in a controller after saving to a database?

I'm following a tutorial on Laravel, adding to a DB via a form. At the end of a function that saves to a DB, it returns back to the page where the form is, but I want to be taken to another page where the information is displayed. In the tutorial I created a controller with a function that returns a view containing all the database info - that element works fine however I can't seem to find a way of calling this function directly after saving to the database. I can also return any other view which just displays static view ( just html with no data handling ). Is what I'm trying to achieve possible?
public function store(){
$li = new \App\LTest1();
$li->creator = request('creator');
$li->title = request('title');
$li->views = request('views');
$li->save();
return back(); // this works
// return view('info'); // this works
//return ('Listings#showList'); this doesnt work = how do i call a function in a controller???
}
// routing
Route::get('info', function () {
return view('info'); // i can get to this static page from my store() function
});
Route::get('thedataviewpage', 'Listings#showList'); // you can route to this but not from the store() function
Redirect is the thing you need here
public function store() {
$li = new \App\LTest1();
$li->creator = request('creator');
$li->title = request('title');
$li->views = request('views');
$li->save();
return redirect('info'); // Redirect to the info route
}
Take this example. Be sure to add the proper route name and a proper message.
return redirect()->route('put here the route name')->with('success', 'Created.');'
to return to a controller action just use
return redirect()->action('Listings#showList');
or you can use route to call that controller action
return redirect('/thedataviewpage');

consuming webservice laravel

I have two projects in laravel, one only with my vision (AppView) and another with the web service (AppWs), in my web service I have the following route
Route project AppWs
Route::group(['prefix' => 'api'],function(){
Route::group(['prefix' => 'user'], function(){
Route::group(['prefix' => 'tipoprojeto'], function(){
Route::get('','Painel\TipoProjetoController#All');
});
});
});
when I access http://localhost/WebServiceApp/public/api/user/tipoprojeto/
it returns me an array with all the data, until then all right.
in my other project, I have a TypeProjectController controller and I have my index () method (AppView), so how can I retrieve the webservice data to load here?
EDIT
AppWs responsible for manipulating the data
public function All(){
return $this->ModelTipoProjeto->paginate(5);
}
AppView responsible for displaying data
Route::resource('/Painel/TipoProjeto', 'Painel\TipoProjetoController');
public function index()
{
$getData = `http://localhost/WebServiceApp/public/api/user/tipoprojeto/` // <~~
return view('Painel.TipoProjeto.index');
}
Retrieve the data that the AppWebservice link returns
First of all in order to consume an external service you have to perfrom a http request towards the endpoint where you intend to get the data form.
Your endpoing: http://localhost/WebServiceApp/public/api/user/tipoprojeto/
Install guzzle which is a php curl wrapper to perform http calls.
In your root dir open command line and inject guzzle in your project by firing :
composer require guzzlehttp/guzzle
Make sure you import guzzle at the top of the controller by adding
use GuzzleHttp\Client;
Then go to your index method and do the following:
public function index(){
// Create a client with a base URI
$client = new GuzzleHttp\Client(['base_uri' => 'http://localhost/WebServiceApp/public/api/user/tipoprojeto/']);
// Send a request to http://localhost/WebServiceApp/public/api/user/tipoprojeto/
$response = $client->request('GET', 'test');
// $response contains the data you are trying to get, you can do whatever u want with that data now. However to get the content add the line
$contents = $response->getBody()->getContents();
dd($contents);
}
$contents contains the data now you can do whatever you want.

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

Resources