How To Make Validations With Requests In Laravel 8? - php

I am using Laravel 8.
I am trying to validate inputs for creating users in the store method of my controller using requests.
Store method of my user controller
UserController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserCreateRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function store(UserCreateRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => Hash::make($request->input('password')),
]);
return response($user, 201);
}
}
UserCreateRequest.php is the file I used to make validation.
UserCreateRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserCreateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|min:3|max:25',
'email' => 'required|email',
];
}
}
But the problem is I get this error
{
"message": "Method Illuminate\\Validation\\Validator::validateRequierd does not exist.",
"exception": "BadMethodCallException",
"file": "/app/vendor/laravel/framework/src/Illuminate/Validation/Validator.php",
"line": 1395,
"trace": [
{
"file": "/app/vendor/laravel/framework/src/Illuminate/Validation/Validator.php",
"line": 554,

Looks all good, but it seems you made a typo somewhere because it tries to call validateRequierd and not validateRequired. You probably wrote requierd somethere in your validation rules.

Related

My Laravel Controller function is not executed when adding custom request

I am new to Laravel. I decide to apply my understanding on Laravel to create a simple registration API.
This API will receive three data which are name, email, and password. These input data will be validated inside the Request file. But I found that, if I use the RegisterUserRequest $request inside my Controller file, the method inside controller file is not executed.
Here is my AuthController file:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\RegisterUserRequest;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(RegisterUserRequest $request)
{
return response()->json([
'message' => 'Here',
]);
}
}
Here is my RegisterUserRequest file
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Foundation\Http\FormRequest;
class RegisterUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
];
}
}
Here is my route
Route::group(['namespace' => 'App\Http\Controllers\Api'], function () {
Route::post('register', [AuthController::class, 'register']);
});
Here is the output show on Postman:
Because suppose the output show on Postman would be:
{
"message": "Here"
}
But it don't. So i think that the register method inside the AuthController is not executed.
Is anyone know the problem? Really Appreciated!!!
Thank you.
As you defined, the user is not authorized to make this request:
public function authorize()
{
return false;
}
Set it to true.

Trait method hasTooManyLoginAttempts has not been applied

I have upgraded my project from 5.2 to 5.3 in laravel. after that, I have the following error:-
Trait method hasTooManyLoginAttempts has not been applied, because there are collisions with other trait methods on App\Http\Controllers\Auth\AuthController in D:\xampp1\htdocs\clubmart_frontend\
app\Http\Controllers\Auth\AuthController.php on line 19
Following is the code of my AuthController:-
<?php
namespace App\Http\Controllers\Auth;
use App\Contracts\Repositories\UserRepositoryInterface;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Voucher;
use App\Services\CartManager;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Validator;
use Illuminate\Http\Request;
use App\Events\UserWasRegistered;
use Event;
use Auth;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviours. Why don't you explore it?
|
*/
use AuthenticatesUsers, RegistersUsers;
public $guard = 'web';
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/** #var UserRepositoryInterface */
protected $userRepository;
/**
* Create a new authentication controller instance.
*
* #param UserRepositoryInterface $userRepository
*/
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
*
* #return Validator
*/
protected function validator(array $data)
{
return Validator::make(
$data,
[
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]
);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
*
* #return User
*/
protected function create(array $data)
{
return $this->userRepository->create(
[
'name' => $data['email'],
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => $data['password'],
]
);
}
protected function authenticated(Request $request, User $user)
{
if($user = Auth::user()) {
if(!empty(app(CartManager::class)->getItems())) {
return redirect()->intended('/cart');
}
else {
return redirect()->intended('/');
}
}
else {
return redirect()->intended('/');
}
}
//overwrite for add flash message to session
public function postRegister(Request $request, User $user)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
//login the newly created user
\Auth::login($this->create($request->all()));
//fire up the send user email event
$user_id = $user->find(\Auth::user()->id);
Event::fire(new UserWasRegistered($user_id));
$request->session()->flash('alert-success', 'Registration successful!');
if(!empty(app(CartManager::class)->getItems())) {
return redirect()->intended('/cart');
}
else {
return redirect($this->redirectPath());
}
}
/**
* Log the user out of the application.
* overwrite for clear user from session
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
if($request->session()->has('user_id'))
$request->session()->forget('user_id');
\Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
}
This is the code of Controller.php:-
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
// use Illuminate\Foundation\Auth\Access\AuthorizesResources;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
Any help will be appreciated. thanks in advance.
Edit
I have removed the following things as suggested:-
use Illuminate\Foundation\Auth\ThrottlesLogins;
use ThrottlesLogins;
But after that I have the following error:-
Trait method guard has not been applied, because there are collisions with other trait methods on App\Http\Controllers\Auth\AuthController in D:\xampp1\htdocs\clubmart_frontend\app\Http\Controllers\Auth\AuthController.php on line 19
I think use ThrottlesLogins already lives in AuthenticatesUsers trait, so you are getting a collision as techically it's included twice. Can you check if it exists in AuthenicatesUsers trait?
If so, try removing use ThrottlesLogins on your AuthController.
This was the solution:-
I simply added the following method to the AuthController.php.
public function getLogin(){
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('auth.login');
}
I have changed $this->guestMiddleware() to 'guest' in AuthController.php
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
// $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
$this->middleware('guest', ['except' => 'logout']);
}
I also have removed the following:-
use Illuminate\Foundation\Auth\RegistersUsers;
use RegistersUsers;
This solved the problem and me successfully able to log in and the project was updated from 5.2 to 5.3. thanks to all for the help.

Laravel form request class not found

I'm trying to create laravel form validation, so I created a form validation with the following code. The problem is that I'm getting an error "Class App\Http\Requests\RegisterForm does not exist" when I typehint the request in controller. Any help would be much appriciated. Thanks
RegisterForm.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterForm extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name': 'required',
'email': 'required',
'mobile_number': 'required',
];
}
}
UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\RegisterForm;
class UserController extends Controller
{
public function register(RegisterForm $request) {
}
public function login() {
}
}
Laravel version 5.7
NGINX
php7.2
the issue was caused by using colon (:) instead of => in rules array
return [
'name'=> 'required',
'email'=> 'required',
'mobile_number'=> 'required',
];

Filter data in form request in Laravel 5.5

I have generated new form Request for the controller, but I do not know how to filter data before there will handle in the validator and so on.
Are there some native solutions in Laravel for this case?
class TestRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
"title" => "required|string",
"order" => "required|integer"
];
}
}
class TestController extends Controller
{
public function store(TestRequest $request, $chapterId)
{
// some business logic
}
}
There is some solution in Laravel 5.5 but in this example author uses
validate for filtering data from request, but I need to use filter inside TestRequest
$data = $this->validate(request(), [
//...
]); // I can't use this inside TestRequest
You can use my package: https://github.com/mikicaivosevic/laravel-filters
It's allows you to filter request values before validation...
<?php
class LoginRequest extends FormRequest {
//Filter
public function filters()
{
return [
'name' => 'lower',
'id' => 'int',
];
}
//...
}
Convert $request->name value into lowercase.
Conert $request->id value into integer.

Laravel 5.2 request validation with Dingo(JWT) Api

Laravel 5.2 request validation is not working in dingo(JWT) API.
When I try to call controller method I use request validation that time it returns blow error.
Error
{"message":"500 Internal Server Error","status_code":500}
Controller
namespace App\Api\V1\Controllers;
//use App\Http\Requests;
use Illuminate\Http\Request;
use App\Api\V1\Controllers\ApiController;
use App\Http\Requests\StoreBlogPost;
//use Request;
use DB;
class CommonController extends ApiController {
public function getCabinet(StoreBlogPost $request) {
$postData = $request->all();
$floorkey = $postData ['FloorKey'];
}
}
Request
namespace App\Http\Requests;
use App\Http\Requests\Request;
class StoreBlogPost extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize() {
return False;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules() {
return [
'FloorKey' => 'required',
];
}
public function response(array $error) {
//Can't get json responce validation error in Controller
return response()->json(['error' => $error], 422);
}
}
Change request class App\Http\Requests\Request to Dingo\Api\Http\FormRequest

Categories