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;
}
Related
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.
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.
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',
]);
}
}
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
I'm using Sentry2 package in my laravel 4 application (http://docs.cartalyst.com/sentry-2/).
I create a new User model that extends Sentry2 User Model:
<?php namespace App\Models;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends \Cartalyst\Sentry\Users\Eloquent\User implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
when I execute the follow code I have a exception.
$adminUser = User::create(array(
'email' => 'admin#admin.com',
'password' => "admin",
'first_name' => 'Admin',
'last_name' => 'Admin',
'activated' => 1,
));
Error:
[RuntimeException]
A hasher has not been provided for the user.
If you want to create your object from Eloquent mass alignment you can add the Hasher manually Like that :
$user->setHasher(new Cartalyst\Sentry\Hashing\NativeHasher);
Or to be permanent you can add a "boot" method to your User object like this :
class User extends \Cartalyst\Sentry\Users\Eloquent\User implements UserInterface, RemindableInterface {
// ...
public static function boot()
{
self::$hasher = new Cartalyst\Sentry\Hashing\NativeHasher;
}
// ...
}
I need to update the config file of sentry package:
'users' => array(
/*
|--------------------------------------------------------------------------
| Model
|--------------------------------------------------------------------------
|
| When using the "eloquent" driver, we need to know which
| Eloquent models should be used throughout Sentry.
|
*/
'model' => '\App\Models\User',
/*
|--------------------------------------------------------------------------
| Login Attribute
|--------------------------------------------------------------------------
|
| If you're the "eloquent" driver and extending the base Eloquent model,
| we allow you to globally override the login attribute without even
| subclassing the model, simply by specifying the attribute below.
|
*/
'login_attribute' => 'email',
),
and use Sentry::getUserProvider()->create() method
$adminUser = Sentry::getUserProvider()->create(
array(
'email' => 'admin#admin.com',
'password' => "admin",
'first_name' => 'Admin',
'last_name' => 'Admin',
'activated' => 1,
)
);
what it tell you is you have to hash and salt your password
so
$adminUser = User::create(array(
'email' => 'admin#admin.com',
'password' => Hash::make('admin'),
'first_name' => 'Admin',
'last_name' => 'Admin',
'activated' => 1,
));
I extended the Sentry User Model like you and the same error is returned, then i find an idea in https://github.com/cartalyst/sentry/issues/163 and then tried passing a new instance of NativeHasher; i'm not sure if this is the correct way, but in the first test the user was saved correctly:
$user = new User;
$user->setHasher(new Cartalyst\Sentry\Hashing\NativeHasher);
$user->first_name = "Name";
$user->last_name = "Last";
$user->password = 'admin';
$user->email = "email#gmail.com";
$user->save();