Laravel Form Request validation by method name - laravel

i have a controller with 5 methods store / rename / duplicate / move / delete
comming from deferent Forms with POST.
And i want to use Form Request for Validation like that :
any adea on how to validate all my forms without creating a request form file for each Form.

You can use $this->route()->getActionName() to the get the current action. ie. MyController#store, MyController#rename, MyController#delete, ...
Then in your SectionRequest you can do something like this:
public function rules(){
$arr = explode('#', $this->route()->getActionName());
$method = $arr[1]; // The controller method
switch ($method) {
case 'store':
// do something.
break;
case 'rename':
// do something.
break;
case 'delete':
// .... and so
}
}

Related

Flash message library does not show message if not with view method

I need to return parameters to get in my javascript. However, if I use a different way to return the view, the flash message doesn't work. If I use the view method to return to the view, the parameter is not passed because the url returned is the url that is called when submitting the form.
I don't know what else to do, I need help.
I'll leave part of my controller code.
In it there will be the way I am returning with the view method trying to insert a parameter and the way I return with a parameter but the flash message does not return anything
public function confirmEmail(Request $request)
{
// Step one
// Check the recaptcha
$recaptcha = GoogleReCaptchaV2::verifyResponse($request->input('g-recaptcha-response'))->isSuccess();
if (!$recaptcha) {
flash('Recaptcha invalido. Tente novamente!')->error();
return view('login', ['error' => 1, 'recaptcha' => $recaptcha]);
// return redirect()->route('login', ['error' => 1, 'recaptcha' => $recaptcha]);
}
...
blade
...
#include('flash::message')
...

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 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

Yii2 validation on controller action

I am developing a Yii 2.0 application in which users can create orders then send the orders to review and after that it follows a number of stages in the workflow.
Everything is ok until yesterday that the customer ask for the possibility that before sending the orders to review the order are considered as draft. Which means I have to turn off validations on create and validate them when users clicks Send To Review button. I know Yii 2.0 supports scenarios but maybe scenarios doesn't apply to this because the Send To Review button is shown in a readonly view. This forces me to do validation inside the controller action because there is no send_to_review view. How can this be done (I mean model validation inside controller action)?
Here is the controller action code
public function actionSendToReview($id)
{
if (Yii::$app->user->can('Salesperson'))
{
$model = $this->findModel($id);
if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
{
$model->orden_stage_id = 2;
$model->date_modified = date('Y-m-d h:m:s');
$model->modified_by = Yii::$app->user->identity->username;
//TODO: Validation logic if is not valid show validation errors
//for example "For sending to review this values are required:
//list of attributes in bullets"
//A preferred way would be to auto redirect to update action but
//showing the validation error and setting scenario to
//"send_to_review".
$model->save();
$this::insertStageHistory($model->order_id, 2);
return $this->redirect(['index']);
}
else
{
throw new ForbiddenHttpException();
}
}
else
{
throw new ForbiddenHttpException();
}
}
What I need to solve is the TODO.
Option 1: Showing validation errors in the same view and the user has to clic Update button change the requested values save and then try to Send To Review again.
Option 2: Redirecting automatically to update view already setting scenario and validation errors found in the controller.
Thanks,
Best Regards
You can use $model ->validate()for validation in controller.
public function actionSendToReview($id)
{
if (Yii::$app->user->can('Salesperson'))
{
$model = $this->findModel($id);
if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
{
$model->orden_stage_id = 2;
$model->date_modified = date('Y-m-d h:m:s');
$model->modified_by = Yii::$app->user->identity->username;
//TODO: Validation logic if is not valid show validation errors
//for example "For sending to review this values are required:
//list of attributes in bullets"
//A preferred way would be to auto redirect to update action but
//showing the validation error and setting scenario to
//"send_to_review".
//optional
$model->scenario=//put here the scenario for validation;
//if everything is validated as per scenario
if($model ->validate())
{
$model->save();
$this::insertStageHistory($model->order_id, 2);
return $this->redirect(['index']);
}
else
{
return $this->render('update', [
'model' => $model,
]);
}
}
else
{
throw new ForbiddenHttpException();
}
}
else
{
throw new ForbiddenHttpException();
}
}
If you don't need validation in actionCreate().Create a scenario for not validating any field and apply there.

conditional nested routes in laravel

I want to check segment of particular URL on route and based on value of segment decide it to handle to another route.Somewhat like below:
Route::get('{module}/{seg}', function(){
if (is_numeric((Request::segment(3)) {
return Route::get('{module}/{seg}',Request::segment(2) . 'Controller#index');
}else{
return Route::get('{module}/{seg}',Request::segment(2).'Controller#index' . Request::segment(3));
}
});
I don't think above code works but can anyone suggest a working code for implementing above logic in laravel?
I'd suggest adding it as an optional parameter, and handle differences in the controller. Given your code, it might look like this, for instance:
// route
Route::get('{module}/{seg}/{param?}', 'Controller#index');
// controller
public function index($module, $seg, $param = null)
{
// for dynamic index methods
if (is_numeric($param)) {
$method = 'index' . $param;
return $this->{$method}();
}
// for non-numeric third-segment params, continue here as usual
}

Resources