I have an app in laravel and I have 3 Admin, owner, user roles, I want that when a user registers he can choose between user and owner, for now I will use the registry of laravel / ui, I will leave them my relationships and my tables
Model Role
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users(){
return $this->belongsToMany('App\User');
}
}
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
public function roles(){
return $this->belongsToMany('App\Role');
}
/* Validations */
// The roles are received in the authorizeRoles variable, and they are validated if my role is valid or not, when accessing a page, the helpers abort generates an http exception and the user receives an error
public function authorizeroles($roles){
if($this->hasAnyRole($roles)){
return true;
}
abort(401,'This action is unauthorized');
}
// Function, where we iterate (HasAnyRole) Enter the roles to check if you have any role
public function hasAnyRole($roles){
if(is_array($roles)){
foreach($roles as $role){
if($this->hasRole($role)){
return true;
}
}
}else{
if($this->hasRole($roles)){
return true;
}
}
return false;
}
// HasRole function - We validate if our user contains the role for which it is asked -->
public function hasRole($role){
if($this->roles()->where('name',$role)->first()){
return true;
}
return false;
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'provider', 'provider_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
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, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'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([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
I would like to know how to filter between only two roles in my controller and paint them in my view in a select, I would appreciate your support
In Controller
$roles = Role::whereIn('name', ['owner', 'user'])->get();
//And pass this roles in your view for example:
return view('user.create', compact('roles');
In view, in form:
<select name='role_id'>
#foreach($roles as $role)
<option value="{{$role->id}}">{{$role->name}}</option>
#endforeach
</select>
Related
I am beginner in Laravel. I make my application in Laravel 8 and spatie/laravel-permission.
Actually i have persimmons: individual|company
Route::group(['prefix' => '', 'middleware' => ['role:individual|company']], function () {
Route::get('/cms-historia-przesylek-nadanych', 'Account\SendPackageController#index')->name('cms-history-send-packages')->middleware('company');
Route::get('/cms-przesyleka-nadana/{id}', 'Account\SendPackageController#show')->name('cms-view-send-package')->middleware('company');
Route::get('/cms-przesyleka-nadana-zwrot/{id}', 'Account\SendPackageController#returnBackPackage')->name('cms-view-send-package-return')->middleware('company');
Route::post('/cms-przesyleka-nadana-zwrot/zamow-paczke/{id}', 'Account\SendPackageController#orderPackage')->name('cms-view-send-package-return-order')->middleware('company');
Route::get('/cms-pobierz-przesyleke-nadana/{id}', 'Account\SendPackageController#getPdf')->name('cms-get-send-package')->middleware('company');
Route::get('/cms-historia-przesylek-odebranych', 'Account\ReceivedPackageController#index')->name('cms-history-received-packages')->middleware('company');
Route::get('/cms-przesyleka-odebrana/{id}', 'Account\ReceivedPackageController#show')->name('cms-view-received-package')->middleware('company');
Route::get('/cms-pobierz-przesyleke-odebrana/{id}', 'Account\ReceivedPackageController#getPdf')->name('cms-get-received-package')->middleware('company');
Route::get('/cms-dwu-stopniowa-weryfikacja', 'Account\TwoStepVerificationController#index')->name('cms-two-step-verification');
});
And this is my USER.php:
<?php
namespace App\Models;
use App\Traits\ScopeActiveTrait;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class User extends Authenticatable
{
use Notifiable,
ScopeActiveTrait,
HasRoles,
SoftDeletes,
HasSlug;
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom(['company_name', 'id'])
->slugsShouldBeNoLongerThan(250)
->saveSlugsTo('slug');
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'enable',
'company_id',
'surname',
'email_verified_at',
'description',
'is_company',
'package1',
'package2',
'package3',
'sms',
'phone',
'street',
'building_number',
'city',
'postal_code',
'revicer_default_inpost_parcel',
'shipping_default_inpost_parcel',
'file_name',
'nip',
'company_name',
'remember_token',
'subdomain',
'lng',
'lat',
'show_map',
'ofert_type',
'discount_value1',
'discount_value2',
'discount_value3',
'discount_value4',
'discount_value5',
'is_two_step_authorization',
'two_step_authorization_token',
];
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'company_id' => 'integer',
'enable'=>'boolean',
'isCompany'=>'boolean',
'show_map'=>'boolean',
];
/* User Login history */
public function loginHistory()
{
return $this->hasMany('App\Models\UserLoginHistory');
}
/* User images */
public function images()
{
return $this->hasManyThrough('App\Models\UploadFile', 'App\Models\User', 'id', 'file_id');
}
public function mainImage()
{
return $this->images()->where('file_type', 'DZ_ADMIN');
}
/* Admin Avatar */
public function getAvatar()
{
return $this->images()->where('file_type', 'DZ_ADMIN')->orderBy('order', 'ASC')->first();
}
public function isCompany(): bool
{
return $this->is_company == 1;
}
}
When I have is_two_step_authorization = 1.- then I need run new middleware for 2 step authorization,.
How can I make it?
is_two_step_authorization = 0 - 2 factorial authorization is disabled. is_two_step_authorization = 1 - Two-factor authentication is enabled.
I think use this tutorial: https://www.itsolutionstuff.com/post/laravel-8-two-factor-authentication-with-smsexample.html but this middleware work always for route with middleware 2fa.
In my case, selected routs may require 2-step security (if the user has chosen so in the settings) or not (the user has disabled security).
How can I change the code from the tutorial to get it?
You need to update the middleware from the tutorial in order to only redirect to 2fa index if the logged user has is_two_step_authorization on. Of course you may need other checks, or to ensure that the user is logged in and so on, but just for this specific usecase, this line of code should do the trick.
app/Http/Middleware/Check2FA.php
public function handle(Request $request, Closure $next)
{
if ($request->user()->is_two_step_authorization && !Session::has('user_2fa')) {
return redirect()->route('2fa.index');
}
return $next($request);
}
Tweak the code from that example...
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Session;
class Check2FA
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if ($request->user()->is_two_step_authorization == 1) {
return redirect()->route('2fa.index');
}
return $next($request);
}
If the requested user has the property of is_two_step_authorization with value one only then it will redirect to the 2fa page, otherwise not
I am working on a project where the database on sql server already existed, so I had to change the names of the tables and columns to run the user registry. Registration works perfectly, now, login does not work. When trying to login, the page does nothing, just reload. If you could help me, I would appreciate it very much, thanks
------------User model--------------
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
protected $table = 'tb_postulantes';
protected $primaryKey = 'id_postulante';
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'nombre_postulante', 'appaterno_postulante', 'correo_postulante', 'password_postulante',
'apmaterno_postulante', 'telefono_postulante', 'fechaingreso_postulante', 'estado_postulante'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password_postulante', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
-------RegisterController----------
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
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 = '/';
/**
* 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, [
'nombre_postulante' => ['required', 'string', 'max:255'],
'correo_postulante' => ['required', 'string', 'email', 'max:255', 'unique:tb_postulantes,correo_postulante'],
'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([
'nombre_postulante' => $data['nombre_postulante'],
'correo_postulante' => $data['correo_postulante'],
'password_postulante' => Hash::make($data['password']),
'appaterno_postulante' => $data['nombre_postulante'],
'apmaterno_postulante' => $data['nombre_postulante'],
'telefono_postulante' => $data['nombre_postulante'],
'fechaingreso_postulante' => '2012-02-21T18:10:00',
'estado_postulante' => '1',
]);
}
}
----------LoginController--------
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function beforelogin()
{
return view('Auth.beforelogin');
}
}
well first of all Laravel authentication uses field 'email' to login user - you dont have this field in your User model so if you want to change this you have to define username in your LoginController like so:
public function username()
{
return 'correo_postulante';
}
And for different password field you can use accessor in your User Model like so:
public function getAuthPassword()
{
return $this->password_postulante;
}
You can find some more informaction in Laravel Documentation https://laravel.com/docs/5.5/authentication#included-authenticating
But if you want to use all three parameters to log in users I will recommend making your own LoginController with different logic.
I'm using Laravel 6.5 still new to PHP and Laravel. When I register successfully, it returns me back to the same registration form with its inputs empty, it successfully registers the user, tho, but won't redirect. I've tried overriding the redirectPath() function as well which isn't working.
When i tried overriding other methods (such as ShowRegistrationForm() ) it worked perfectly, but I can't get it to redirect.
The redirect works perfectly for the login controller.
Here is my RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
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
*/
public $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/** Overrriding native method */
public function showRegistrationForm(){
$this->authorize('register', User::class);
return view('auth.register');
}
/**
* 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:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
return redirect()->to($this->redirectTo);
}
}
and web.php with my route
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
})->name('welcome');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
/** Since we can't register without login in. I'll try to do the 'registering' by myself. */
Route::post('/users', 'HomeController#store');
/** In here we will try and do all 7 resource methods in one line of code */
Route::resource('trabajos', 'TrabajoController');
/** Ruta para que el admin vea todos los trabajos de los usuarios */
Route::get('/usuarios', 'AdminController#index');
/** Ruta para eliminar alguno */
Route::delete('usuarios/{usuario}', 'AdminController#delete')->name('admin.delete');
Route::get('/usuarios/{usuario}', 'AdminController#show');
/** Tratando de setear el Price de un trabajo específico */
Route::post('/setPrice/{trabajoId}', 'AdminController#setPrice');
/** Updateando información de trabajos de otros usuarios */
Route::get('/usuarios/{usuario}/trabajo/{trabajo}/edit', 'AdminController#editJob');
/** Patching it */
Route::patch('/usuarios/{usuario}/trabajo/{trabajo}', 'AdminController#updateJob');
/** Filtering */
Route::get('/usuarios/{usuario}/filtro', 'AdminController#filter');
/** Getting a pdf */
Route::get('/usuarios/{usuario}/pdf','AdminController#export_pdf');
and my homeController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
/** From here and down, it's mine */
public function store(){
$data=request()->validate([
'name' => 'required',
'email' => 'required|email',
'password' => 'required|min:5|confirmed',
]);
/* User::create($data); */
$user = new User;
$user->name = request()->name;
$user->email = request()->email;
$user->password = bcrypt(request()->password);
$user->save();
return back();
}
}
In action store change back() to redirect() - >route('home'). Best Regards.
after successful registration – you get redirected where? To default /home URL, or whatever is specified in $redirectTo property in RegisterController.
So, how to customize it and make Laravel “remember” the previous page for registration, too?
So you should override register method in RegisterController, for doing this you can copy the register method that is in this location
vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php
and change it like this in your RegisterController.
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect()->intended($this->redirectPath());
}
You have to redirect on register action, not create action
Here is my RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
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
*/
public $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:web');
}
/** Overrriding native method */
public function showRegistrationForm(){
return view('auth.register');
}
/**
* 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: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([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect()->intended($this->redirectPath());
}
}
i try to make login with facebook use socialite. I had register on developers.facebook.com and got my APP_ID and Secret_code and i had implement it in my .env file and config/services.php. But when after i input my username and password facebook it can't direct me to homepage. i used authentication scaffolding from laravel
Error
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Socialite;
use Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
/**
* Obtain the user information from provider. Check if the user already exists in our
* database by looking up their provider_id in the database.
* If the user exists, log them in. Otherwise, create a new user then log them in. After that
* redirect them to the authenticated users homepage.
*
* #return Response
*/
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect($this->redirectTo);
}
/**
* If a user has registered before using social auth, return the user
* else, create a new user object.
* #param $user Socialite user object
* #param $provider Social auth provider
* #return User
*/
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->name,
'email' => $user->email,
'provider' => $provider,
'provider_id' => $user->id
]);
}
}
.env
FB_ID=321**14684*****
FB_SECRET=40fb4782*****5b7b88391f4599f18c7
FB_URL=https://localhost:8000/auth/facebook/callback
web.php
Route::get('/', function () {
return view('homepage');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('auth/{provider}', 'Auth\LoginController#redirectToProvider');
Route::get('auth/{provider}/callback',
'Auth\LoginController#handleProviderCallback');
**App\User.php**
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','provider','provider_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Config/services.php
'facebook' => [
'client_id' => env('FB_ID'),
'client_secret' => env('FB_SECRET'),
'redirect' => env('FB_URL'),
],
Please give me some advice to solve this problem. I'm sorry for my bad English. Thank you.
I've made a referral system on my laravel project v5.4 but I have 2 issues with that:
My users referral link will load index page of my website instead of loading register page. (How I fix it?)
When user register with referral link nothing will happen in database of the person who invited new user and also new user him/herself. (How I get info in both users tables?)
I simply used this tutorial to get my referral system:
https://brudtkuhl.com/building-referral-system-laravel/
This is my CheckReferral Middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Response;
use Closure;
class CheckReferral
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if( $request->hasCookie('referral')) {
return $next($request);
}
else {
if( $request->query('ref') ) {
return redirect($request->fullUrl())->withCookie(cookie()->forever('referral', $request->query('ref')));
}
}
return $next($request);
}
}
This is my UserController
public function referral() {
$user = User::find(1);
return view('users.referral', compact('user'));
}
Here is my route:
Route::get('/referral', 'UserController#referral')->name('referral');
My RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Cookie;
use DB;
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 = '/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',
'username' => 'required|string|max:255|unique:users',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'g-recaptcha-response' => 'required|captcha',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$referred_by = Cookie::get('referral');
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'affiliate_id' => str_random(10),
'referred_by' => $referred_by,
]);
}
User Model
protected $fillable = [
'name', 'username', 'email', 'password', 'affiliate_id', 'referred_by',
];
And That's it!
if this is for registration the right way to do this is first in your routes you should have a optional input like ..
Route::get('/register/{referral?},'Auth\RegisterController#registerPage');
then in that controller
public function registerPage($referral=0)
{
return view with the $referral variable ..
}
in your view .. your form should look like this ..
<form action="/register/{{ referral }}" method="post" ..... >
back to your route ..
Route::post('/register/{referral},'Auth\RegisterController#doRegister');
in your controller again ..
public function doRegister(Request $request, $referral)
{
$request->merge(['referred_by' => $referral]);
}
so your referred_by is either 0 or other value .. it's up to you how you handle the validation ..
Add register page url in the value in this part -> url('/')
#if(!Auth::user()->affiliate_id)
<input type="text" readonly="readonly"
value="{{url('/').'/?ref='.Auth::user()->affiliate_id}}">
#endif
Question number 1:
I think you should add {{url('/register')}} here instead of {{url('/')}} to make it look this way:
#if(!Auth::user()->affiliate_id)
<input type="text" readonly="readonly"
value="{{url('/register').'/?ref='.Auth::user()->affiliate_id}}">
#endif
If that's how your register route endpoint is defined.