How to catch QueryException error when using Laravel Auth - laravel

I tested my app to disallow duplication of emails. It works, however I can't catch the error or it doesn't display the request error in the form page whenever it found duplication.
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'admin#DOMAIN.com' for key 'admins_email_unique'
I already tried overriding the RegisterController, but still can't find where the error is being fetch first.
protected function create(array $data)
{
try{
return Admin::create([
'role_id' => $data['role_id'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
catch(Illuminate\Database\QueryException $e)
{
echo($e);
}
}
My current RegisterController
<?php
namespace App\Http\Controllers\AdminAuth;
use App\Admin;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Traits\RoleTrait;
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;
use RoleTrait;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/admin/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('admin.guest');
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return Admin::create([
'role_id' => $data['role_id'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* 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, [
'role_id' => 'required|string|max:4',
'username' => 'required|string|unique:users|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
$mgaAdminRoleNames = $this->getAdminRoleNames();
return view('admin.auth.register')->with('adminRoleNames',$mgaAdminRoleNames);
}
/**
* Get the guard to be used during registration.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('admin');
}
I already put in admin\auth\register.blade.php
#if ($errors->has('email'))
<span class="invalidMessage">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
The expected solution either of this two:
1) Display error in the form page like this:
Image Here
2) Or catch the QueryException and echo the error directly

use validations for duplicate entry i hope this link will be helpful laravel recommended link

I found an answer while I'm checking the validator. So if anyone encounter this problem. Here's the solution:
protected function validator(array $data)
{
return Validator::make($data, [
'role_id' => 'required|string|max:4',
'username' => 'required|string|unique:admins|max:255',
'email' => 'required|string|email|max:255|unique:admins',
'password' => 'required|string|min:6|confirmed',
]);
}
Notice the "unique" attribute. I change it from "users" to "admins".
I think the word "admins" came from config\auth.php directory where you set your guards and providers stuff.

Related

Redirecting to previous page after registration in laravel 7

i want to redirect to a previously accessed page right before accessing the registration page after a user has successfully registered themselves. I edited the registration controller as below although i get the following exception View [http:..127.0.0.1:8000.prices] not found. I cross checked my routes and everything is fine. Here is my register controller.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\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, [
'fname' => ['required', 'string', 'max:255'],
'lname' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'phonenumber' => ['required', 'string', 'min:10', 'max:10'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'fname' => $data['fname'],
'lname' => $data['lname'],
'email' => $data['email'],
'phonenumber' => $data['phonenumber'],
'password' => Hash::make($data['password']),
]);
}
/**
* Show the application's registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
if(session('link')) {
$myPath = session('link');
$registerPath = url('/register');
$previous = url()->previous();
if($previous = $registerPath) {
session(['link' => $myPath]);
}else{
session(['link' => $previous]);
}
}else{
session(['link' => url()->previous()]);
}
return view('auth.register');
}
protected function redirectTo()
{
if(session('link')){
return view(session('link'));
}
return view('/');
}
}
I think the issue is most likely to be with the function:
protected function redirectTo()
{
if(session('link')){
return view(session('link'));
}
return view('/');
}
I tried replacing return view(session('link')); with return url()->previous(); but there was no luck. I am using laravel 7.
The issue was actually with adding view. Instead of return view(session('link')); use return (session('link')); Same applies to the return outside the if statement.
try to use redirect back
return Redirect::back();
do not forget to import redirect in controller
use Redirect;

How to read URL parameters in laravel

I am begginer, and trying to create a referral system. following is sample url
http://dev.lea.com/register?ref=mh2HPLpVSn
I try to get referral string. how can i get separately? is there need of middleware for getting cookies? if yes then what will be code of middleware? and how can i get referral reference in RegisterController?
Here is my Register Controller.
<?php
namespace Lea\Http\Controllers\Auth;
use DB;
use Lea\User;
use Lea\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Cookie;
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 = '/';
/**
* 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, [
'fname' => 'required|string|max:255',
'lname' => 'required|string|max:255',
'referral' => 'string|max:255',
'username' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
// 'tracking_id' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \Lea\User
*/
protected function create(array $data, Request $request)
{
// printing here referral Link
echo $request()->ref;
// $referred_by = Cookie::get();
// print_r($referred_by);
die;
return User::create([
'fname' => $data['fname'],
'lname' => $data['lname'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'affiliate_id' => str_random(10),
// 'referred_by' => $referred_by,
'identity' => $data['identity'],
'dob' => $data['dob'],
'board_id' => $data['board_id'],
'class_id' => $data['class_id'],
'subject_id' => $data['subject_id'],
'institute' => $data['institute'],
'address' => $data['address'],
'city' => $data['city'],
'std_mobile' => $data['std_mobile'],
'father_name' => $data['father_name'],
'father_mobile' => $data['father_mob'],
'ipadress' => \Request::ip(),
]);
}
}
When you have an URI such as /register?ref=mh2HPLpVSn you can retrieve ref like this:
$request()->ref
in your controller! I believe you can also use $request()->has('ref') to determine if it's present in the URI.
Hope this helps you!!
In laravel 6+ inside controller you can use like
$request->get('ResourcePath')
You can get your parameters using Request access.
Here one example for get your ref code:
public function register(Request $request)
{
$allParams = $request->all();
$refParam = $request->ref;
dd($allParams, $refParam);
...
}
public function showRegister(Request $request) {
var_dump(request->ref)
}
then you can do things like validation and so on, another possiblity is to change the template of your register form and add a hidden field with the refcode from the ref param and handle the whole request in your register method.

Laravel Guzzle conflicts with /register Route::auth()

I'm new to use Laravel. I'm using Laravel 5.2. I've implemented Auth for user register and login. It is work properly. After installed Guzzle via composer and after that implementing sending email, it works like a charm. But after try to submit register user, the data which sent via POST form, not saved in table. How to keep data recorded in table meanwhile sending email still works?
AuthController for handling user registration:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\PencapaianBadge;
use DB;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* 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, [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'username' => 'required|max:10|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
//Ambil id user dengan menhitung jumlah rows
$id = DB::table('users')->count();
/*PencapaianBadge::create([
'id_user' => $id+1,
'id_badge' => 1,
]);*/
$Pencapaian = new PencapaianBadge();
$Pencapaian->id_user = $id+2;
$Pencapaian->id_badge = 1;
$Pencapaian->save();
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id' => 2,
'path_image' => 'main/resources/assets/images/user_profiles/default.png',
]);
}
}

Route is not found -logout

I am trying to click on logout button, but it returns an error:
NotFoundHttpException in RouteCollection.php line 161:
There's no getLogout in Authcontroller, and it worked before, not sure why now it isn't.
AuthController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = "dashboard";
protected $loginPath = 'auth/login';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* 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|max:255',
'email' => 'required|email|max:255|unique:users',
'username' => 'required|max:20|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
}
}
Routes.php:
Route::get('auth/logout', 'Auth\AuthController#getLogout');
view:
Logout
Try
Logout
Or give your route a name
Route::get('auth/logout', ['as' => 'logout', 'uses' => 'Auth\AuthController#getLogout');
and do
Logout

Laravel 5.1 - Store Data in Eloquent: Relationships

I folowing Official Laravel 5.1 User Authentication to create User Login and User Register and it is run well.
But now, I add another table, user_detail table, which contain another data of user like first/last name, gender, etc. This table has one to one relationship with user table. And I already defining relationships like hasOne and belongsTo.
I want to ask, how when I registered a new user, the both user and user_detail table is filled? Although the user_detail tables just filled in the 'id' only, because the user table and user_detail table have same id for primarykey and foreignkey.
For reference here my routes:
...
// Registration routes...
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
...
AuthController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\UsersDetail;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers,
ThrottlesLogins;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* 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|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data) {
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
protected $redirectPath = '/dashboard';
}
Here is one way of doing it.
$user = new \User($data)->save();
$user_detail = new \UserDetail($detail_data);
$user->user_detail()->associate($user_detail);
Okay, I think #ajameswolf method is to update data. What I need is to create a data in two table which have relation.
I use this method in my AuthController.
protected function create(array $data) {
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user_detail = UsersDetail::create([
'birthOfDate' => null
]);
$user->save();
$user_detail->save();
return $user;
}

Resources