Append errors with custom error - laravel

How can i append the $errors->all() array? Like a custom error message... Searched on the internet but i did not find anything.
In my view:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
My controller:
<?php
namespace App\Http\Controllers\Admin;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
/**
* #param Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required',
]);
if ($user = Auth::attempt([
'email' => $request->email,
'password' => $request->password
])) {
/** #var $user User */
if ($user->isAdmin()) {
return redirect()
->route('admin.dashboard');
}
}
// wrong email or password
return redirect('/admin/login');
}
}

First use Validator facade for validation and then
$inputs = $request->all();
$rules = array(
'email' => 'required|email|exists:users,email',
'password' => 'required',
);
$messages = array();
$validator = Validator::make($inputs,$rules,$messages);
$validator->after(function($validator) {
//do some stuff
$validator->errors()->add('error', 'error messgae');
})

custom error message :
return redirect('/admin/login')->withErrors([
'error_key' => 'error_message'
]);
and if you want flush old inputs :
return redirect('/admin/login')->withInput()->withErrors([
'error_key' => 'error_message'
]);

You should write this
<?php
namespace App\Http\Controllers\Admin;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
/**
* #param Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required',
]);
if ($user = Auth::attempt([
'email' => $request->email,
'password' => $request->password
])) {
/** #var $user User */
if ($user->isAdmin()) {
return redirect()
->route('admin.dashboard');
}else {
return redirect('/admin/login')->>with('errors', 'Sorry!!! something went wrong. please try again.');
}
}else {
return redirect('/admin/login')->>with('errors', 'Sorry!!! something went wrong. please try again.');
}
// wrong email or password
return redirect('/admin/login');
}
}

You can add to errors while using Validator Facade for validation:
$validator = Validator::make(
[
'email' => $request->email,
'password' => $request->password
],
[
'email' => 'required|email|exists:users,email',
'password' => 'required',
]
);
$validator->errors()->add('custom-error', 'my custom error');

Related

Validation in Fast Excel package Laravel

ImportController
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Talent\ImportData\Requests\ImportDataRequest;
use Illuminate\Support\Facades\Hash;
use Rap2hpoutre\FastExcel\FastExcel;
class ImportController extends Controller
{
public function __construct(private User $user)
{
}
public function import(ImportDataRequest $request)
{
$validated = $request->validated();
$collection = (new FastExcel)->import($validated['file'], function ($rows) {
$user = $this->user->create([
'name' => $rows['First Name'] . " " . $rows['Last Name'],
'email' => $rows['Email'],
'password' => Hash::make('Introcept#123'),
'role' => $rows['Role']
]);
$employee = $user->employees()->create([
'status' => $rows['Status'],
'first_name' => $rows['First Name'],
'last_name' => $rows['Last Name'],
'email' => $rows['Email'],
'contact_number' => $rows['Contact Number'],
'date_of_birth' => $rows['Date of Birth'],
'current_address' => $rows['Current Address'],
'pan_number' => $rows['Pan Number'],
'bank_account_number' => $rows['Bank Account Number'],
]);
$education = $employee->education()->create([
'education_level' => $rows['Education Level'],
'passed_year' => $rows['Passed Year'],
'institution' => $rows['Institution'],
]);
$employment = $employee->employment()->create([
'organization' => $rows['Organization'],
'join_date' => $rows['Join Date'],
'current_position' => $rows['Current Position'],
'work_schedule' => $rows['Work Schedule'],
'team' => $rows['Team'],
'manager' => $rows['Manager'],
'superpowers' => $rows['Superpower'],
]);
$employment->manages()->create([
'employee_id' => $rows['Manages'],
]);
});
}
}
ImportData Request
<?php
namespace App\Talent\ImportData\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ImportDataRequest 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 [
'file'=>'required|mimes:csv,xlsx'
];
}
}
I am creating an API where the admin can import data from an excel file. Here, I am using the Fast Excel package in order to import data. Everything is working fine, but I have no idea how I can validate excel data before saving it into the database. I am pretty new to Laravel and any help will be really appreciated. Thank you

Laravel User Class was not found

I ran into a Laravel problem trying to access the build-in class on Laravel named 'User', basically I want to create new users. But I get the error saying this: 'Undefined type 'App\Http\Controllers\User'.intelephense(1009)`. What is the fix?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function register(Request $request){
$validator = Validator::make($request->all(),[
'name' => 'required',
'email' => 'required|email',
'password' => 'required'
]);
if($validator->fails()){
return response()->json(['status_code']);
};
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
return response()->json([
'status_code' => 200,
'message' => 'User was saved!'
]);
}
}
You forgot to import the User class:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
// this is the default for Laravel 8+, before it was App\User
use App\Models\User;
class AuthController extends Controller
{
public function register(Request $request){
$validator = Validator::make($request->all(),[
'name' => 'required',
'email' => 'required|email',
'password' => 'required'
]);
if($validator->fails()){
return response()->json(['status_code']);
};
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
return response()->json([
'status_code' => 200,
'message' => 'User was saved!'
]);
}
}

Laravel redirecting a user after register doesn't work when Registered event is fired

My register method of the RegisterController:
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
Auth::login($user);
event(new Registered($user));
return redirect()->route('account.index');
}
If I go through this flow the user is authenticated and the event is fired, but the user is not redirected... Now for the confusing part: if I move the redirect line above the event line, it does work (but obviously the event doesn't fire):
Auth::login($user);
return redirect()->route('account.index'); // User is correctly redirected here
event(new Registered($user));
What's happening here?
Full RegisterController:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function showRegistrationForm()
{
return view('auth.register');
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
Auth::login($user);
event(new Registered($user));
return redirect()->route('account.index');
}
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data, array $ua)
{
$user = User::create([
'email' => $data['email'],
'password' => Hash::make($data['password']),
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
]);
return $user;
}
}
Try to authenticate user with id :
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
Auth::loginUsingId($user->id);
event(new Registered($user));
return redirect()->route('account.index');
}

Laravel 5.8 register redirect

I'm using Laravel 5.8, still new to PHP and Laravel. When I register, it returns the user in JSON format which is normal from the Register Users.php register function. However, I have a redirectTo() function which should take care of the redirect and redirect the user to some pages a specified, but it's not working. I've tried overriding the redirectPath() function as well which isn't working.
The redirect works perfectly for the login controller.
Any solution or pointers would be appreciated. See RegisterController below.
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Auth;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
//public $redirectTo = '/home';
protected function redirectPath()
{
$role = Auth::user()->role;
if ($role === 'candidate') {
return '/candidate_dashboard';
} elseif ($role === 'employer') {
return '/employer_dashboard';
} elseif ($role === 'contractor') {
return '/contractor_dashboard';
}
}
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
try {
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'role' => ['required', 'string', 'max:50'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
} catch (Illuminate\Database\QueryException $th) {
return back()->withError($th->getMessage())->withInput();
}
}
protected function create(Request $data)
{
try {
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'role' => $data['role'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
} catch (Illuminate\Database\QueryException $th) {
return back()->withError($th->getMessage())->withInput();
}
}
}

JSON errors of LoginController and RegisterController should be strings not arrays

I am using Laravel 5.5.14 (php artisan --version). I am using Laravel to create just a REST API.
When I get errors, the shape of it looks like this:
[
'message' => 'The given data was invalid.',
'errors' => [
'email' => ['The email field is required.'],
'password' => ['The password field is required.']
]
]
My
We see inside the errors array, each field (email, password) instead of being strings, is an array of a single string. Can there ever be more then one error is this why it is an array? Even if there is more then one error, I wanted to tell Laravel just report the first error without an array, is this possible?
In my api.php I have this:
Route::post('login', 'Auth\LoginController#login');
Route::post('logout', 'Auth\LoginController#logout');
Route::post('register', 'Auth\RegisterController#register');
My LoginController.php looks like this:
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->attemptLogin($request)) {
$user = $this->guard()->user()->load('pets');
$user->generateToken();
return $user;
}
return $this->sendFailedLoginResponse($request);
}
public function logout(Request $request)
{
$user = Auth::guard('api')->user();
if ($user) {
$user->api_token = null;
$user->save();
}
return ['ok' => true];
}
And my RegisterController.php looks like this:
public function __construct()
{
$this->middleware('guest');
}
/**
* The user has been registered.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function registered(Request $request, $user)
{
$user->generateToken();
return response()->json($user, 201);
}
/**
* 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',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
Override validateLogin to the following or you could give it a different name and call it from your controller function-
public function validateLogin($request){
$rules = [
'user_name' => 'required|string',
'password' => 'required|string',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
$errorResponse = $this->validationErrorsToString($validator->errors());
return response()->json(['message' => 'The given data was invalid.', 'errors' => $errorResponse],400);
}
}
And make another function to transform your response to expected format with this method-
private function validationErrorsToString($errArray) {
$valArr = array();
foreach ($errArray->toArray() as $key => $value) {
$valArr[$key] = $value[0];
}
return $valArr;
}
And don't forget to add this at the start of your controller file-
use Validator;
Hope this helps you :)
From the docs:
The $errors variable will be an instance of Illuminate\Support\MessageBag
An example of displaying errors from the docs:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Resources