Registration redirct on condition based in laravel - php

How can I redirect to specific path after registration in Laravel?. I want to redirect page on id after registration. please help me.
Thank You, in advanced..

If you want to run custom logic after user registers, you'll need to implement registered() method in the controller that registers users:
protected function registered(Request $request, $user)
{
$path = ...; //determine path to redirect to
return redirect($path);
}

I found the answers, Just add $this->redirectTo = ' / ' in Auth/RegisterController.php
Auth/RegisterController.php
Like This:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$this->redirectTo = '/';
return $user;
}

Related

Check if record exists while registering user

In my Register controller - I have the following method to check if a record exists in another table before creating a user:
public function getCompanyDetails($id)
{
$details = Company::where('company_id', $id)->first();
return $details;
}
protected function create(array $data)
{
$company_id = $data['com_id'];
$company_details = $this->getCompanyDetails($company_id);
if ($company_details == null) {
return redirect()
->back()
->with('warning', 'We could not find the company');
} else {
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
However when the company record is not found. I'm getting the following error message:
Cannot use object of type Illuminate\Http\RedirectResponse as an array
I believe it's expecting a return of type user. But how can I redirect back to the registration page if the company is not found?
Thanks in Advance
Try the method withErrors():
Redirect::back()->withErrors(['warning', 'We could not find the company']);
I however recommend you to use the validation rule Exists instead of having more queries and manually return a message. You can do it like so:
$request->validate([
'company_id' => 'required|integer|exists:App\Company,id',
]);
Then you won't need the extra logic and the other method.
Source: https://laravel.com/docs/7.x/validation#rule-exists

laravel 5.8 Auth/RegisterController custom redirect on validation failure

I'm using Laravel 5.8, I have a single page that has both the Registration and Login forms (2 separate forms posting to the respective endpoints/controllers)
My Registration Form posts to the Auth/RegistrationController as provided by Lavarel Auth.
I would like to change the behaviour so that on an unsuccessful registration attempt it will add an additional parameter to redirect url so I know which form to apply to validation feedback too.
I'm already aware of the redirectTo variable this appears to be for successful requests though
You need to override the Auth/RegistrationController::register method, take a look at the default code provided by the framework and adjust it to your needs something like this:
public function register(Request $request) {
if ($this->validator($request->all())->fails()) {
return redirect('/foo?bar=1');
}
// Copy the default behaviour here
...
// or you can just
return parent::register($request);
}
You can simply overwrite parent function to create new user in same
Auth/RegistrationController create new method as
/**
* 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' => Hash::make($data['password']),
]);
}
Here, in '$data' variable you will get all of the parameters which you have passed through form.
For error checking you can just check for,
Laravel global error variable $errors is null or not
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
if(!empty($errors)){
if($data['form'] == 'form_1'){
$redirectTo = 'fitst_form'
}
else if($data['form'] == 'form_2'){
$redirectTo = 'second_form'
}
}
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
I hope this will solve your problem
You have to set register method in app/Http/Controllers/Auth/RegisterController.php
protected function register(Request $request)
{
$errors = ['error'=>'yout errors list];
if(!empty($errors)){
return redirect()->route('/register-errorpage')->withInput()->withErrors($errors);
}
}

Laravel- Creating new user only if there is data in another table

I have two tables the first one is the user table which have these property id, username, email,remember_token, createdat, updateat another table is called received_pay having id, email, token my task is to check if the email, and token entered by the user must match the ones in received_pay otherwise new user is not created, thanks for your time in advanced,
I'm trying to create new user on a condition that if there is data in another table then new user is created otherwise not I have put my code inside if else statement and is throwing errors.
my function for creating new user is listed below:
protected function create(array $data)
{
/*$exists = \DB::table('received_pay')->where('email', $data['email'])->first(); */
$exists=\DB::table('received_pay')->where('email', '=', $data['email'])->where('token', $data['token'])->exists();
if ($exists === null)
{
// user doesn't exist
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'token' => $data['token'],
]);
}
else
{
return null;
}
}
I think that the best approach in Laravel is create a middleware to protect this url. If you already have this create user feature working is better don't modify it.
So the first step would be create a middleware (https://laravel.com/docs/5.5/middleware) to add your safeguard, something like this:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckPayment
{
public function handle($request, Closure $next)
{
$payment = \DB::table('received_pay')->where('email', $request->email)->where('token', $request->token]);
if (!$payment->count()) {
return redirect('no-payment');
}
return $next($request);
}
}
Then you would need to create a route to handle this invalid creation users (this no-payment url).
And finally you can protect your create-user url in route, by adding your middleware in your kernel.php file...
protected $routeMiddleware = [
...
'payment' => \App\Http\Middleware\CheckPayment::class,
];
and in your web.php route file:
Route::post('user', 'UserController#create')->middleware('payment');
In this way your code will look cleaner, tidier, and closer to the way Laravel works.
I hope it would work fine for you.
If you wish to do it with if statement then do it like below
protected function create(array $data)
{
/*$exists = \DB::table('received_pay')->where('email', $data['email'])->first(); */
$exists=\DB::table('received_pay')->where('email', '=', $data['email'])->where('token', $data['token']);
if (!$exists->count())
{
// user doesn't exist
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'token' => $data['token'],
]);
}
else
{
return null;
}
}
the count() in the if is to make the statement evaluate true if the data exists and false otherwise and create the new user.
I think that solves your problem.

laravel registration : add error to validation generated outside of validation

so this is my register controller
protected function validator(array $data)
{
return Validator;
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
register here
}
I want to add a referral system to this process basically when registering user might send a refer_id (id of a user who has referred this user to website), I'll check that refer id and if it was valid I'll do some my thing
I want to change my validation function to something like
protected function validator(array $data)
{
$validation = Validator::make($data, [
'email' => ['required' ,'email' , 'max:255', Rule::unique('users')->where('rep_id' , $this->rep->id) ] ,
'password' => 'required|string|min:6|confirmed',
'name' => 'required|max:255',
'last_name' => 'required|max:255',
'refer_id' => 'present|numeric',
]);
if(isset($data['refer_id']))
{
$refer = User::find($data['refer_id']) ;
if($refer)
{
// return error : refer id is wrong !
}
}
return $validation ;
}
my problem is this part
// return error: refer id is wrong!
how can I return registering the user with this error back to view or add this error to validation errors?
Laravel has a clean approach to do this
try this
'refer_id' => 'nullable|exists:users,id'
or may be
'refer_id' => 'present|numeric|exists:users,id'

How to assign default user role in entrust?

I just want to assign a role to newly registered user. How I can achieve this in Laravel 5 with Entrust? I am using Entrust for roles and permissions.
Last time I tried to fire event after user registration in a file in vendor folder. Is there any way to fire an event for role assignment without modifying anything inside vendor folder?
If yes then where should I fire event? I don't want to modify anything inside my vendor folder like firing event in postRegister() in AuthenticatesAndRegistersUsers.php because new updates will overwrite my code.
Code on this link looks good but I don't know entrust has registration event or not.
http://laravel.io/forum/07-02-2014-entrust-assign-role-on-user-signup
Here is my code in routes.php:
// this event is firing on user login and i am getting user object
Event::listen('auth.login', function($user) {
var_dump($user);
die(__LINE__);
});
// this event is not firing on user registration
Event::listen('auth.register', function($user) {
var_dump($user);
die(__LINE__);
// $donor_role = DB::table('app_roles')->where('name', '=', 'donor')->pluck('id');
// $user->roles()->attach($donor_role);
// return false;
});
Please help me out.
App\Service\Registrar.php
This is my way:
public function create(array $data)
{
$create = User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => $data['password'],
]);
$user = User::find($create->id);
$role = Role::where('name', '=', 'user')->firstOrFail();
$user->roles()->attach($role->id);
return $create;
}
I figured it out all by myself. Here is how I achieved:
I copied postRegister() function from /vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php and overridden in /app/Http/Controllers/Auth/AuthController.php with some modification.
Here is the modified function in AuthController.php:
public function postRegister(Request $request) {
$validator = $this->registrar->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
$this->auth->login($this->registrar->create($request->all()));
// little modification :-)
\Event::fire('auth.assign_default_role', $this->auth->user());
return redirect($this->redirectPath());
}
And here is the event listener in routes.php:
Event::listen('auth.assign_default_role', function($user) {
$donor_role = DB::table('app_roles')->where('name', '=', 'donor')- >pluck('id');
$user->roles()->attach($donor_role);
return false;
});
You can fire the register event from your controller where the actual signup is being handled.
Event::fire('auth.register', array($user));
In Laravel 5.7+ you can go to the RegisterController and modify the create function:
protected function create(array $data) {
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$default_role = Role::where('name', 'DEFAULT_ROLE_NAME')->first();
$user->attachRole($default_role);
return $user;
}
Don't forget to use App\Models\Role; in the beginning.

Categories