I just want to validate API requests using laravel custom Request Handler. For this I have created a RegisterRequest, with the following content.
<?php
namespace App\Http\Requests\Api\Auth;
use App\Http\Requests\Request;
class RegisterRequest 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 [
'email' => 'required'
];
}
}
And, I want it to use in AuthController as:
use App\Http\Requests\Api\Auth\RegisterRequest;
public function postRegister(RegisterRequest $request)
{
dd($request->all());
}
But, neither the validation nor the request parameters are shown in the respose.
All the routing are working fine, but the query paremeters are empty. Any help will be appriciated.
Version: Laravel: 5.1
I want to let laravel handle all request parameters and say API whether the request is made successful or with errors.
Your authorize method should return true. If it is false , RegisterRequest will return forbidden because you are not authorize to use this RegisterRequest class . So, change your authorize method from RegisterRequest to this :
public function authorize()
{
return true;
}
Edit :
If you want to reply the error message in your way you can override the response method in RegisterRequest method like this :
public function response(array $errors)
{
return \Response::json($errors);
}
Related
I have a problem with my API on laravel. I created a SupportController that i've added to my routes/api.php
My controller :
<?php
namespace App\Http\Controllers;
use App\Http\Requests\SupportRequest;
class SupportController extends Controller
{
public function store(SupportRequest $request) {
if($request->validate())
{
return response()->json('success', 200);
} else {
return response()->json('error', 400);
}
}
}
My routes :
Route::post('/support', [SupportController::class, 'store']);
And postman return :
{
"Laravel": "8.83.18"
}
Actually, i tryied to fix my cache using php artisan cache:clear and php artisan route:clear.
I got this message in my server console:
closed without sending a request it was probably just an unused speculative preconnection
Edit:
Here is my supportRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SupportRequest 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 [
'message' => ['required', 'min:10']
];
}
}
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.
I'm facing a problem with custom request. I have created a request with php artisan make:request StoreNewClient.
I have configured the validations logic inside the new request file, like:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreNewClient extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [ ...
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [ ...
];
}
}
In the controller, I imported the file like use App\Http\Requests\StoreNewClient; and after, In the function store() I writed:
public function store(StoreNewClient $request)
{
// Will return only validated data
$validated = $request->validated();
...
}
That what I understood from the documentation, but this give me an error: Class App\Http\Requests\StoreNewClient does not exist but exists (!!).
I already tried to clear caches and dumped the composer but didn't solved the problem. Any help?
Fount the error. In the messages(), 1 line didn't had the comma at the end and neither the app neither the composer dump-autoload, gave any error.
I make some gate like this:
Gate::define('update-post', function ($user, Post $post) {
return $user->hasAccess(['update-post']) or $user->id == $post->user_id;
});
I checked my database and it has update-post access and the user id is same as in the post. but I got:
This action is unauthorized.
errors. so am I do some mistake here? thanks.
I had a similar problem some time ago when starting to use Form Request classes for data validation. I noticed the following:
If you are using Form Requests to validate data, then first of all, check that you set properly the authorization rule that will allow it to pass. This is handled by the authorize() method that must return a boolean, that by default is set to false:
namespace App\Http\Requests\Users;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class UpdateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
/**
* By default it returns false, change it to
* something like this if u are checking authentication
*/
return Auth::check(); // <-------
/**
* You could also use something more granular, like
* a policy rule or an admin validation like this:
* return auth()->user()->isAdmin();
*
* Or just return true if you handle the authorisation
* anywhere else:
* return true;
*/
}
public function rules()
{
// your validations...
}
}
Make sure you return true on "authorize" method
public function authorize()
{
return true;
}
For Laravel 8(also applicable to Laravel 9) go to
folder app->http->requests
choose the class file(in my case it was StoreStudentRequest.php) and in function authorize set return value to true;
public function authorize()
{
return true;
}
This problem occurred to me when I did not return true in php artisan make:request SellRequest
in functionpublic function authorize()
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SellRequest 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 [
'city'=>'required',
'address'=>'required',
'type'=>'required',
'land'=>'required',
'area'=>'required'
];
}
}
<?php
namespace App\Modules\UserManagement\Request;
use Illuminate\Foundation\Http\FormRequest;
use Response;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'full_name' => 'required',
'email' => 'required|email',
'password' => 'required',
're_enter_password' => 'required'
];
return $rules;
}
}
In my case, I was not doing the right check in Gate::define(...)
So maybe double check your logic in that function
Need to authorize function return true
public function authorize()
{
return TRUE;
}
and then add auth facade or use Auth;
If you have already configured your authorize() and you still have the same problem, you may check your route/api.php You may have a error declaring the same path for 2 Controller.
Route::resource('users', UserController::class)/*authorized true*/;
Route::resource('users', User2Controller::class)/*unauthorized true*/;
add this line in your controller
**use Illuminate\Http\Request;**
instead of
use App\Http\Requests\StoreGameRequest;
and change the parameter in function as
public function store(**Request $request**)
{
$request->validate([
I want to use Form Requests to validate Model so i started by create php artisan make:request TaskRequest and after i add in TaskRequest class `
public function rules()
{
return [
'name' => 'required|min:5',
];
}
public function messages()
{
return [
'name.required' => 'A title is required',
];
}
`
and in My logic
Route::post('/tasks',function (\App\Http\Requests\TaskRequest $request){
$task = new \App\Task();
$task->name = $request->input("name");
$task->save();
return response()->json(['task was created',$task], http_response_code());
});
So when i try to add a task i get error HttpException, This action is unauthorized.,AuthorizationException ...
It was work for me without Validation. So how can i fix this issue ?
Every (self-created) request has an authorize function that determines if the user is allowed to send the request. This can be useful to check for admin privileges or similar.
In you case, you can simply return true. More information can be found in the corresponding docs
Your authorize function in your TaskRequest would look like this:
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
In your custom request class for "form request" which contains the validation logic pass return:true; instead of return:false; and then it will work like a charm.
The code will look like something as following,
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class portfolioValidate 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',
'content'=> 'required'
];
}
}
as you can use middleware to make authentication for the page which contains this form... so we don't need that authorization in the FormRequest class. So returning true will make it(validation) authorized for all cases.
I think now it is clear to everyone now.