Validation, not self - php

I am using Laravel 5.5.14 and created a request or validation with php artisan make:request CreateInviteRequest.
I want the user to not be able to invite themselves.
Is there a way to give a proper error saying "cannot be self"?
Right now I accomplished this with 'not_in:'.Auth::guard('api')->user()->id like this:
public function rules(Request $request)
{
return [
'invite_user' => ['numeric', 'exists:users,id', 'not_in:'.Auth::guard('api')->user()->id]
];
}
This gives error message The selected invite_user is invalid.

define messages
public function messages()
{
return [
'invite_user.not_in' => 'cannot be self',
];
}

You can add ID to ignore as third parameter to the exists() rule:
'invite_user' => 'numeric|exists:users,id,' . auth()->id(),

u can achieve this by Not In.
public function rules(Request $request)
{
return [
'invite_user' => 'required|email|unique:users,email',
Rule::notIn([Auth::guard('api')->user()->id]),
];
}

Related

Flash message is not displayed when redirecting to route

I have the following code to associate a contact to a lead:
public function selectSalesConsultant($uuid)
{
$lead = Lead::where('uuid', $uuid)->firstOrFail();
return view('dealer-contacts.select_consultant')
->with(compact('lead'));
}
public function updateSalesConsultant(Request $request, $uuid)
{
$lead = Lead::where('uuid', $uuid)->firstOrFail();
$lead->update([
'contact_id' => $request->get('contact_id')
]);
Flash::success('Sales Consultant information updated for the lead.');
return to_route('select-sales-consultant', ['uuid' => $uuid]);
}
In my second function, after the lead is updated, I'd like to display a success message:
Flash::success('Sales Consultant information updated for the lead.');
return to_route('select-sales-consultant', ['uuid' => $uuid]);
Here is what I have in my view:
#include('flash::message')
Here is how the route is defined inside routes/api.php:
Route::get('/select-sales-consultant/{uuid}', [App\Http\Controllers\LeadController::class, 'selectSalesConsultant'])
->name('select-sales-consultant');
Nothing gets displayed. If, instead of redirecting, I do a return view(), the message does get displayed.
What's the proper way of doing this? I'm using the Laracasts Easy flash notifications package.
Looks like it was because I was using an API route.
I added the following to my Kernel.php, and it resolved the issue.
'api' => [
\Illuminate\Session\Middleware\StartSession::class,
//etc
],
Please check app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
...
\Illuminate\Session\Middleware\StartSession::class,
...
],
....
];
and then try to use quest->session()->flash()function.
public function updateSalesConsultant(Request $request, $uuid)
{
...
//Flash::success('Sales Consultant information updated for the lead.');
$request->session()->flash('success', 'Sales Consultant information updated for the lead.');
...
}

Laravel Validation Request, how to handle validation on update?

First of all I love the way that validation is going through, can now easily use
public function authorize(Authenticator $auth)
{
return $auth->user()->hasRole('administrator');
}
hat's not the problem, I bump always into another problem... that is when you update an record, how to do things with the rules? If I need to update an email, I need the following string: 'email' => 'unique:users,email_address,10'. In this case it should look like:
public function rules()
{
return [
'email' => 'required|unique:users,id,?????',
'tags' => 'required'
];
}
It's more simple.
The Laravel documentation says "If your table uses a primary key column name other than id, you may specify it as the fourth parameter":
'email' => 'unique:users,email_address,'.$user->id.',user_id'
If for example, you want to verify if a username exists, but excluding current user ID:
// UpdateUserRequest.php
public function rules() {
//
return [
'username' => 'required|unique:users,username,' . $this->id . ',id',
];
}

Problem with the function update() using Repository pattern to write REST API

I have a problem that all the create-read-delete using Repository Pattern is good but the update function is error. I still have the data but the information is not updated.
This is my code in EventController
public function update(EventRequest $request, $id)
{
$events = $this->repository->update($request->all());
return $this->sendResponse($events->toArray(), 'Successfully updated the Event!!');
}
This is i use DI for inject from the Repository, this is EventRepository.php
public function update($id, array $array) {
$events = $this->model->findOrFail($id);
$events->update($array);
return $events;
}
when i use dd($array) and the result returns [] without anything. Can anyone help me. Did i write anything wrong in this. Or i write the wrong Request
public function rules()
{
// $id = $this->events ? ',' . $this->events->id : '';
return $rules = [
'event_title' => 'required|max:255',
'event_type_id' => 'required|integer|between:1,3',
'from_date' => 'required|date_format:Y-m-d H:i:s',
'to_date' => 'date_format:Y-m-d H:i:s|nullable',
'is_recurring' => 'boolean|required',
'remarks' => 'nullable',
];
}
This method takes two arguments:
public function update($id, array $array) {
However, that's not how you are calling it:
$this->repository->update($request->all());
I take it $request->all() gives you an array, so pass the ID first.
$this->repository->update($id, $request->all());

Laravel, Append Values to Custom Request Error Message

I am building an API, the desired output when there is an error is as follows:
{
"success": false,
"messages" : [
{
"field is missing for example",
....
}
]
}
I have a custom request called when from the controller as follows:
public function store(CoverageValueRequest $request, CoverageValueManager $manager){
$manager->create($request);
return response()->json(['success' => $manager->isSuccessful(), 'message' => $manager->getErrorMessage()]);
}
if the CoverageValueRequest has an error it would through something similar to this:
[
{
"series.0.values.0.cells": [
"The series.0.values.0.cells field is required when none of series.0.values.0.wifi are present."
],
"series.0.values.0.wifi": [
"The series.0.values.0.wifi field is required when none of series.0.values.0.cells are present."
]
}
]
How can I modify the error outcome of the custom request to follow the first posted structure.
Thanks in advance.
All you need to do is implementing your own failedValidation method. Default is
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException($this->response(
$this->formatErrors($validator)
));
}
In fact you should rather leave this method unchanged and implement your own version of default:
protected function formatErrors(Validator $validator)
{
return $validator->getMessageBag()->toArray();
}

Yii2 Custom http exceptions views

In the application login I have the following code that throw ...HttpException on logging errors:
// common/models/LoginForm.php which is called from the backend SiteController actionLogin method as $model = new LoginForm();
public function loginAdmin()
{
//die($this->getUser()->getRoleValue()."hhh");
if ($this->getUser()->getRoleValue() >= ValueHelpers::getRoleValue('Admin') && $this->getUser()->getStatusValue() == ValueHelpers::getStatusValue('Active')){
if ($this->validate()){
return \Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30:0);
}
else{
throw new \yii\web\NotFoundHttpException('Incorrect Password or Username.');
}
}
else{
throw new \yii\web\ForbiddenHttpException('Insufficient privileges to access this area.');
}
}
It is working fine, but I want to customize the page the rendered with each of NotFoundHttpException and ForbiddenHttpException. I tried to search the Yii2 api to find any parameters that may define view in the construct of the object but I could not find that. So, is there any way to custom the view of the exception?
From Mihai P. (Thank you) answer, I have got this answer. I opened the file of the error class at vendor\yiisoft\yii2\web\ErrorAction.php and I have found that it has a public property for view, so, I decided to use it and hence I defined it in the error array of the actions method as follows:
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
'view' => '#common/views/error.php',
],
];
}
Finally, in common folder I had to create a new folder named views and fill it with a view file called error.php with the following simple code
<?php
$this->title = $name;
echo $name;
echo "<br>";
echo $message;
echo "<br>";
echo $exception;
The three variables in the view $name, $message and $exception are supplied from the ErrorAction object and they could be found in the last lines of that file
...
else {
return $this->controller->render($this->view ?: $this->id, [
'name' => $name,
'message' => $message,
'exception' => $exception,
]);
}
...
If you take a look here https://github.com/yiisoft/yii2-app-advanced/blob/master/frontend/controllers/SiteController.php
You can see that it uses an external action to handle the errors
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
You can either create your own ErrorAction file that extends the default one and use yours instead of the default one from Yii, or just comment out that action and create a normal actionError and put it in there.

Categories