I created a custom form request named ClientStoreRequest with the following code:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ClientStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
// return $this->user()->can('add-clients');
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|unique:clients|max:255',
'website' => 'required|url',
'street' => 'required',
'town' => 'required',
'postcode' => 'required|max:8',
'county' => 'required',
'country' => 'required'
];
}
}
I then modified my ClientController's store method to look like this:
/**
* Store a newly created resource in storage.
*
* #param ClientStoreRequest $request
* #return \Illuminate\Http\Response
*/
public function store(ClientStoreRequest $request)
{
dd(1);
}
So when the form is submitted, it should kill the page and print a 1 to the screen. When I use ClientStoreRequest $request, it just sends me back to the page where I submitted the form with no errors and no dd(1) result, however when I utilise Request $request it prints 1 to the screen.
Am I missing something really obvious? I've followed the docs to make this.
Edit: I'm using a resource controller so the route is Route::resource('clients', 'ClientController');
A bit embarrassing but this one was purely down to developer error. The custom form request is actually working correctly... just my rules are referencing one field that I forgot to put into my form so isn't showing the errors to the screen! Once I echoed the usual $errors array I could see my error - I'll blame the late night coding!
Related
I'm using laravel 5.5
I have a Request that I've built but the required rule is not working correctly.
Route
Route::get('v1/learning_centre/user/{userId}/course/list', 'API\LearningCentre#userCourses');
Controller
public function userCourses(GetUserCourses $request)
{
$courses = User::findOrFail($request->userId)
->courses()
->get();
return new CourseResourceCollection($courses);
}
Request
namespace App\Http\Requests\LearningCentre;
use Illuminate\Foundation\Http\FormRequest;
class GetUserCourses 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 [
'userId' => 'required|integer'
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'userId.required' => 'A User is required',
];
} }
If I turn off the required rule I can get to the controller. If I have the required rule in the request I get a 302. I am passing in a valid userId in phpunit. Without the request rules my code works as intended.
Any ideas?
You should be using route model binding to validate a required GET parameter in this situation, not a FormRequest class, which, as the name should indicate, are intended for form requests.
Your route:
Route::get('v1/learning_centre/user/{user}/course/list', 'API\LearningCentre#userCourses');
Your controller:
public function userCourses(User $user) {
If a user ID is missing (or an invalid one used), your controller will automatically throw a ModelNotFoundException, which Laravel by default returns as a 404.
I've been trying to add a FormRequest with rules and message to my delete method, but the request is coming back empty and the rules are failing every time.
Is it possible to get the request data in a delete method?
Here's my request class:
use App\Http\Requests\Request;
class DeleteRequest extends Request
{
/**
* 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 [
'staff_id' => ['required', 'exists:users,uid'],
'reason' => ['required', 'string'],
];
}
/**
* Get custom messages for validator errors.
*
* #return array
*/
public function messages()
{
return [
'staff_id.required' => staticText('errors.staff_id.required'),
'staff_id.exists' => staticText('errors.staff_id.exists'),
'reason.required' => staticText('errors.reason.required'),
'reason.string' => staticText('errors.reason.string'),
];
}
}
And the controller:
/**
* Handle the 'code' delete request.
*
* #param integer $id The id of the code to fetch.
* #param DeleteRequest $request The request to handle the data.
* #return response
*/
public function deleteCode($id, DeleteRequest $request)
{
dd($request->all());
}
Even though the HTTP/1.1 spec does not explicitly state that DELETE requests should not have an entity body, some implementations completely ignore the body which contains your data, e.g. some versions of Jetty and Tomcat. On the other hand, some clients do not support sending it as well.
Think of it as a GET request. Have you seen any with form data? DELETE requests are almost the same.
You can read a LOT on the subject. Start here:
RESTful Alternatives to DELETE Request Body
It seems like that you want to alter the state of the resource rather than destroying it. Soft-deleting is not deleting and thus requires either a PUT or a PATCH method which both support entity bodies. If soft-deleting is not the case, you're doing two operations through one call.
I've got the following request validation:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class OwnerEstate 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 [
'firstname' => 'required_if:type,individual',
'secondname'=> 'required_if:type,individual',
'lastname' => 'required_if:type,individual',
'pin' => 'required_if:type,individual|digits:10',
'name' => 'required_if:type,legal-entity',
'eik' => 'required_if:type,legal-entity|digits:9'
];
}
}
And when the type is not individual it still checks for the 'digits:10' validation of the pin and returns an error. How do I disable the other validation if required_if validation does not require the field. (I'm using Laravel 5.5)
digits:10 is completely separate from required_if, so it will validate whether or not the field is required. However, if you want to also allow null or empty values (assuming the field is not required), you can add the rule nullable.
https://laravel.com/docs/5.5/validation#rule-nullable
I'm building an API, one of the db table Person have 52 columns and most of them are required t don't think the way I'm doing is right
public function store() {
if (! input::get('name') or ! input::get('age') or ! input::get('phone') or ! input::get('address') and so on till the 52 field) {
return "Unprocessable Entity";
}
return "Validated";
}
And how to properly validate all the required fields
Thank You
You can simply write your validation rules and messages within a Request file and can call directly within your store function like as
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Validation\Rule;
/**
* Class YourFileRequest
* #package App\Http\Requests
*/
class YourFileRequest extends Request
{
/**
* 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|unique:posts|max:255',
'body' => 'required',
];
}
/**
* Get the custom validation messages that apply to the request.
*
* #return array
*/
public function messages()
{
return [
'title.required' => 'Please enter title',
'title.max' => 'Please enter max value upto 255',
'body.required' => 'Please enter body',
];
}
}
within your controller
use App\Http\Requests\YourFileRequest;
......
public function store(YourFileRequest $request)
{
//Your storing logic
}
You can do it in two ways:
The first one is
$this->validate($request,['email'=>'required|email|unique']);
Secondly, you can create a separate ValidationRequest by using the following command:
php artisan make:request StoreRequest
I've been struggling with laravel 5.2 login function messages. I've override the default sendFailedLoginResponse function in AuthController which works for failed attempts.
But I need to override the validate function response as well which I could not figure out how to do that. Also I do not want to override the default login functionality in the AuthContrller and want to stick with the same login function.
The reason for overriding the validate function is that am making an angular app and want the response in json format with some custom keys.
Currently default login function in Illuminate\Foundation\Auth\AuthenticateUsers.php
public function login(Request $request)
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
I want the response something like in the below sendFailedResponse function in AuthController
/**
* Get failed request response
*
* #param null
* #return null
*/
public function sendFailedLoginResponse()
{
return response()->json( [ 'status' => false, 'message' => $this->getFailedLoginMessage() ]);
}
Thanks
I don't know anything about Angular and handling json on laravel but I had similar problem while creating custom error message for postLogin function. take a look at this code, perhaps you could do something within form request.
This is my AuthController.php
use App\Http\Requests\LoginFormRequest;
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(LoginFormRequest $request)
{
return $this->login($request);
}
Try using form request on the function postLogin
class LoginFormRequest extends Request
{
/**
* 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 [
'email' => 'required|email',
'password' => 'required|min:6',
];
}
public function messages()
{
return [
'required' => 'Your :attribute is required.',
'min' => ':attribute must be at least :min characters in length.',
'email' => 'Please type valid email address.',
];
}
}
I came up with the solution by implementing JWT for authentication which I could think of is the best solution with Client side.