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.
Related
I am trying to validate input data with a custom form request.
The form request name is UpdatePassword. And i try to run the code by injecting it in my updatePassword() function in my Api/AuthController. I and it just redirects back to home page
<?php
namespace App\Http\Requests\Api;
use Illuminate\Foundation\Http\FormRequest;
class UpdatePassword extends FormRequest
{
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'email' => 'required|string|email|max:255|exists:users,email',
'old_password' => 'required|string',
'password' => 'required|string|confirmed'
];
}
}
My controller
<?php
namespace App\Http\Controllers\API;
use App\Http\Requests\Api\UpdatePassword;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthController extends controller
{
public function updatePassword(UpdatePassword $request){
dd($request->all());
}
}
My Exceptions/Handler.php
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* #var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* #var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* #param \Exception $exception
* #return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
}
Here is my route
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['namespace' => 'Api'], function (){
Route::group(['prefix' => 'user'], function (){
Route::post('changePassword', 'AuthController#updatePassword');
});
});
Here is the postman request and response
[![Here is the postman request and response][1]][1]
when I
try to run the code in postman it as an ajax request it doesn't work. the validation doesn't work. it just renders the home page. localhost:8000
Are you calling the route from postman with the Accept: application/json HTTP header (or the equivalent Content-Type one)?
If you don't put that Laravel doesn't know that you want a json response and would redirect you to the homepage (I think it will default to it because you don't have a referrer header set on your request) with errors in the session.
If validation fails while using a Form request, a redirect response will be generated to send the user back to their previous location. That's why you are redirecting back to the page instead of the response JSON.
Laravel have one protected method "failedValidation" method. You need to overwrite this method in your form request class which is UpdatePassword.php in case above by adding the below code snippet to.
.
.
.
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json($validator->errors(), 422));
}
you can try with this validator syntex. i have used.
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
$temp = $validator->errors()->all();
if ($validator->fails()) {
return response()->json(['Status' =>
false,'Message'=>$temp[0],'Data' => '','Status_code' =>"401" ]);
}
The standard way to validating incoming requests in Laravel is something like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* #return Response
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
}
There’s nothing wrong with validating requests in controllers, But how could I write the validation logic out of the controller to keep it clean and not break Single Responsibility Principle?
You could make your own form Request.
First create a request with php artisan make:request StorePostRequest
Create your own rule in this class like:
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
Update your controller function
public function store(StorePostRequest $request)
{
// do something
}
For more info:
https://laravel.com/docs/5.7/validation#creating-form-requests
Use the form requests provided by Laravel:
https://laravel.com/docs/5.7/validation#creating-form-requests
and make sure your controller uses the ValidatesRequests trait.
Form requests are validated before the controller actions are executed and contain validation rules and authorization logics.
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',
];
I am creating an Admin backend for my laravel project. It is using the laravel Auth scaffolding. I am now getting this error after coming back to it after the weekend and I am struggling to find an error. I have checked all spellings and capitalization. I have ran composer update etc etc but still no luck. Here is the error below, I do have the admin class and its in the namespace App, not sure whats going on:
ReflectionException error class admin does not exist.
Web.php file
Route::prefix('admin')->group(function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.dashboard');
Route::get('/logout', 'Auth\AdminLoginController#logout')->name('admin.logout');
});
AdminLoginController.php
<?php
namespace App\Http\Controllers\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AdminLoginController extends Controller
{
public function __construct()
{
$this->middleware('admin')->except('logout');
}
public function showLoginForm()
{
return view('auth.admin-login');
}
public function login(Request $request)
{
//Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// If successful, then redirect to tehir inteded page
return redirect()->intended(route('admin.dashboard'));
}
// unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
public function logout()
{
Auth::guard('admin')->logout();
return redirect('/');
}
}
AdminController.php
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
class AdminController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('admin');
}
}
Okay so I have fixed it!! In the AdminLoginController, I added this 'guest:admin' to this instead of just 'admin' betweeen the middleware parenthese :
public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}
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