Laravel Default validation message wouldn't appear - laravel-9

I am developing a Laravel backend API. I am trying to build an API that will accept two fields which are name and email with validation.
Here is my controller file:
public function register(RegisterUserRequest $request)
{
// retrieved validated user
$validated = $request->validated();
}
Here is my RegisterUserRequest file:
class RegisterUserRequest 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<string, mixed>
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email:rfc,dns',
];
}
}
I am trying to pass the invalid email format to the backend but the error message not appearing:
I had already set my header to Accept:application/json in my postman.
Is anyone know how to resolve the problem? Really appreciated!
Thanks.

Related

Issue With Laravel 8 Auth Email Verification

I'm Using Laravel 8.x And i'm trying to make login/register With Email verification
I followed Some Tutorials,Blogs but didn't get desired output
I want:-
Whenever User Register themselve An Verification Email must send to there email
(Email Is Sent but not able to verify by that url so i follow some laracast blog by that i'm able to verify by that verification url)
but the issue is if i didn't verified my self i'm still able to login into my application
Here Is Codes
HomeController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(['auth','verified']);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
','--------------------------------------------------------------------------
',' Register Controller
','--------------------------------------------------------------------------
','
',' This controller handles the registration of new users as well as their
',' validation and creation. By default this controller uses a trait to
',' provide this functionality without requiring any additional code.
','
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'contact' => ['required','min:10'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required','string','min:8','confirmed','regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{6,}$/'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'contact' => $data['contact'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
Veification Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use Illuminate\Auth\Access\AuthorizationException;
use App\Models\User;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**
* Where to redirect users after verification.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
// $this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
public function verify(Request $request)
{
// if ($request->route('id') != $request->user()->getKey()) {
// throw new AuthorizationException;
// }
$user = User::find($request->route('id'));
auth()->login($user);
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect($this->redirectPath())->with('verified', true);
}
}
Route
Auth::routes(['verify' => true]);
Route::group(['prefix'=>'user', 'middleware' => 'auth'],function(){});

Laravel 5.5 Rest API Session store not set on request

I am implementing rest api in my laravel project. I want to save the access token which i got from the api response in session. When i tried this code, postman shows this error: Session store not set on request
<?php
namespace App;
use Illuminate\Http\Request;
class AuthSession{
private $oAuthHeader;
private $request;
public function __construct(Request $request)
{
$this->oAuthHeader = [];
$this->request = $request;
}
/**
* #return string
*/
public function getAccessToken()
{
if($this->request->session()->has('accessToken'))
echo $this->request->session()->get('accessToken');
else
return null;
}
/**
* #param string $accessToken
* #return AuthSession
*/
public function setAccessToken($accessToken)
{
$this->request->session()->put('accessToken',$accessToken);
return $this;
}
}

Auth changes are not reflected laravel 5.3

I am new to laravel and want to make few changes like validation for proper email in login and sending user to login page after logout.
I have made these change in AuthenticatesUsers trait but they do not seems working.
I have changed these functions:
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|email', 'password' => 'required',
]);
}
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}
Any help will be appreciated. Thanks.
You should not change AuthenticatesUsers trait . what you can do is override the method in LoginController, so copy paste it into your LoginController
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}
This should work fine.

Laravel 5 - Authorization

I have a Laravel 5 application and require to implement a authorization using middleware. I have used "Entrust" (https://github.com/Zizaco/entrust) for authorization.
My issue is, how I authorize each request (users/index, users/create, users/store etc.) inside of handle method of my middleware.
I can check Auth::user()->can('create-user') but require to check with each request dynamically.
Here's my impelementation of such middleware:
class Authenticate {
public function __construct() {}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$token = \Request::header('x-auth-token');
// common login functionality
if ($token) {
$authtoken = \App\Models\Authtoken::find($token);
if ($authtoken) {
\Auth::loginUsingId($authtoken->user_id);
}
}
return $next($request);
}
}
Authtoken is a eloquent model over authtokens table. Of course you can retrieve a user id some other way.

Error with Laravel authentication

I'm new to Laravel and I am trying to implement authentication in my application, when I post the login form this error is returned in my browser:
I have no idea what this error means, where it occurs, or how to fix it.
This is my signin function in my authentication controller that handles all logins:
public function signin()
{
// validate the info, create rules for the inputs
$rules = array(
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|min:6' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('/authentication')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$user = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($user)) {
// validation successful!
// redirect them to the secure section or whatever
// return Redirect::to('secure');
// for now we'll just echo success (even though echoing in a controller is bad)
return Redirect::to('dashboard.index');
} else {
// validation not successful, send back to form
return Redirect::to('/authentication')
->with('failed', 'Incorrect email / password!');
}
}
}
This is my User model:
<?php
class User extends Eloquent{
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
protected $fillable = array('email','school_id','role_id','activation_key','reset_key','login_status','account_status');
// LINK THIS MODEL TO OUR DATABASE TABLE ---------------------------------
protected $table = 'users';
// DEFINE RELATIONSHIPS --------------------------------------------------
public function roles() {
return $this->belongsTo('Role');
}
public function schools() {
return $this->belongsTo('Institution');
}
public function lectures() {
return $this->hasOne('Lecturer');
}
public function students() {
return $this->hasOne('Student');
}
public function getId()
{
return $this->id;
}
}
Let's take a look at Laravel's default User model:
class User extends Eloquent ...
so far so good
... implements UserInterface, RemindableInterface {
Oooops looks like you're missing something ;)
Also the two traits are not unimportant.
Here's how it should look like:
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
protected $fillable = array('email','school_id','role_id','activation_key','reset_key','login_status','account_status');
// [the rest of your model]