How to insert to database user with default value? - php

I want to register user and I have 3 fields in form; login, password and confirm_password. In database I have column login, password and role. So I want to insert database user which have default role User. This oode below show me error SQLSTATE[HY000]: General error: 1364 Field 'role' doesn't have a default value. How can I resolve this problem ?

You need to add/modify the Role column with your SQL Client, chances are you have not defined a default value to it, and the column is a "Not Null" one meaning you can't insert a row if this column is empty.
Another option is to have something like that with your create function :
$user = User::create([
'login' => $data['login'],
'password' => Hash::make($data['password']),
'role' => "User"
]);

If you create users only with role "User" you can add this line when you create user;
protected function create(array $data)
{
$user = User::create([
'login' => $data['login'],
'password' => Hash::make($data['password']),
'role'=>"User"
]);
$user->assignRole('role');
return $user;
}
Or you can use Observer:
class UserObserver
{
/**
* Handle the "User" created event.
*
* #param User $user
* #return void
*/
public function creating(User $user)
{
if (is_null($user->role)) {
$user->role= "User";
$user->save();
}
}
}

Controller Logic:
$user = User::create([
'login' => $request->login,
'password' => Hash::make($request->password)]);
Model Logic if you want to insert default value
class User extends Model
{
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->role='user';
});
}
}

Related

How to generate and set username in Laravel eloquent?

I have some fields in user table:
id firstName lastName userName
Here I need to generate and save an userName automatically where the user will provide only firstname & lastName. I have tried something like this but not sure about the piece of code.
User.php
class User extends Authenticatable{
...
protected $appends = ['firstName', 'lastName', 'userName'];
protected $attributes = ['userName' => 'default'];
public static function boot()
{
parent::boot(); // TODO: Change the autogenerated stub
self::creating(function ($model) {
$randNum = rand(10, 99);
$userName = $model['firstName'] . $model['lastName'] . $randNum;
$model->userName = $userName;
});
}
}
So whenever I'm trying to migrate & seed it's showing
Field 'userName' doesn't have a default value
The seeder is
public function run()
{
DB::table('users')->insert([
'firstName' => 'Osman',
'sureName' => 'Rafi',
'email' => 'rafi.ogchy#gmail.com',
'password' => Hash::make('password'),
]);
}
What you're looking for is Model events.
First define a static boot method on your model. In there you can then run your username generation code.
class User extends Model
{
public static function boot()
{
parent::boot();
self::creating(function($model){
$randNum = rand(10, 99);
$userName = $model['firstName'] . $model['lastName'] . $randNum;
$model['userName'] = $userName;
});
}
}
This will intercept the creation of your model, and generate the username.
setUserNameAttributes function only works when you set username to model, not works automatically
you need to define setFirstNameAttribute function and inside it generate your username
Note: last word in function name is Attribute not Attributes*

when register, insert data in 3 tables LARAVEL

I work at a project, I started to learn Laravel and I wanted to create a register form where you can put all your information and all the information to be sent in 3 tables.
You have to select if you are a candidate or a employer.
In my database i have those 3 tables: users, profile_employee and profile_employer.
Can someone show me how to create the RegisterController to insert in the table users only email and password, and if they selected candidate to send the rest of information to profile_employee, and if they selected employer to send them to the table profile_employer. Thanks!
This is are my models for ProfilasdasdasdasdasdasdasdasdasdeEmployeer and ProfileEmployee
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProfileEmployee extends Model
{
protected $table = 'profasdasdasdasdile_emploasdasdasdasdyee';
protected $fillable = [
'id','usasdasdasder_id', 'fiasdasdasdasdasdst_name', 'laasdasdst_namasdasdasdasdasde','phonasdasdasde', 'casdasdv', 'picasdasdasdasdture', 'adrasdasdasdasdasdess', 'toasdasdasdasdasdasdwn',
];
protected $hidasdasdasdasdasdden = [];
}
and
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProfileEmployer extends Model
{
protected $tablasdasdasdasde = 'profileasdasdasdasdasdasdasd_emplasdasdasdasdasdasdoyer';
protected $fillabasdasdasdasdle = [
'iasdasdasdd','useasdasdr_iasdasdasdasdasdasd', 'coasdasdasdasdasdmpany_naasdasdasdasdasdme', 'CasdasdasdU_asdasdI', 'phoasdasdasdasdasdne', 'pictasdasdasdasdasdure', 'adasdasdasdasdress', 'towasdasdasdasdasdn',
];
protected $hidasdasdasdden = [];
}
How can I do the RegistasdasdasdasdasdasdasderController?
Without writing any code I think the best way would be to create a polymorphic relationship, there’s some example code in the documentation-
https://laravel.com/docs/5.8/eloquent-relationships#one-to-one-polymorphic-relations
So in your users table you’d have a userable_type and userable_id (not sure if them names are correct). The userable_type column would contain the model name for either your ProfileEmployee table or your ProfileEmployer table and the userable_id the foreign key of the relationship.
As you can see in the documentation you can then retrieve the relationship and laravel will know which model to use by the userable_type column.
Looking at your tables though I think you could merge the profiles into one table and maybe have a metadata column for data which isn’t always stored for both user types.
I think you can do it by creating two separate method for user type to create them by passing user instance in RegisterControlle just like as follow. and dont forget to return user after creating profile.
class RegisterController extends Controller{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
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',
'type' => 'required|in:employee,employer',
]);
}
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
// check the user type
$data['type'] = 'employee' ? $this->createEmployee($user) : $this->createEmployer($user);
}
public function createEmployee($user)
{
// here you can create Employee profile
return $user;
}
public function createEmployer($user)
{
// here you can create Employer profile
return $user;
}
}
Here we need to overwrite two method which is validator and create.

General error: 1364 Field 'remember_token' doesn't have a default value

I m new to laravel. I wanted to insert the admin credentials into database.
public function verify() {
$username = Input::get('username');
$password = Input::get('password');
if (!Admin::count()) {
$user = new Admin;
$user->username = Input::get('username');
$user->password = $user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('/admin/login');
} else {
if (Auth::attempt(array('username' => $username, 'password' => $password))) {
echo("i m in if");
if (Session::has('pre_admin_login_url')) {
$url = Session::get('pre_admin_login_url');
Session::forget('pre_admin_login_url');
return Redirect::to($url);
} else {
$admin = Admin::where('username', 'like', '%' . $username . '%')->first();
Session::put('admin_id', $admin->id);
return Redirect::to('/admin/report')->with('notify', 'installation Notification');
}
} else {
return Redirect::to('/admin/login?error=1');
}
}
Admin Model:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Admin extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'admin';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
I have changed the database to default value to 'null' but still it gives the same error.This was the application built by code-canyon i haven't know about the querying parameter in which files are they exists.
Result:SQLSTATE[HY000]: General error: 1364 Field 'remember_token'
doesn't have a default value (SQL: insert into admin (username,
password, updated_at,
created_at)values(admin#taxinow.com,y$csyEcrhERoQEszmxNmiOG.bcAZtwC8xeGiF2xyKTd2YLhEbjixm.m,2017-09-21
08:34:24, 2017-09-21 08:34:24))
Any help would be appreciated. Thanks.
i solved this issue on my application, and i want you to try the same..
go to your users table and edit the remember_token field, update the default column to NULL.
once this is done, try running the application again, it should work this time. But if you were using migrations to update your database schema(fields/properties), you could rollback and make this adjustment to that column by adding this nullable() to the remember_token string...
$table->string('remember_token')->nullable();
i hope this helps.
Regards.
Go to Admin model and add it to the $protected fillable as an array
protected $fillable = [
'user_name','remember_token',
];

extend laravel 5 built-in authentication to login only "if user == active"

I use the included authentication of laravel 5.1.6 and want to know how I can extend it, to work like this:
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
If the user is not "active", the login should not be possible. I have an 'active' column in the users table , with 0 or 1 as value. How can i do this while still using the built in authentication with login throtteling.
edit:
I don't have a postLogin function in the AuthController, only a use AuthenticatesAndRegistersUsers, ThrottlesLogins; , a __construct(), a validator() and a create() function. Do I have to change something in the trait in Illuminate\Foundation\Auth\.. or must I add the the postLogin() function in the AuthController ?
You can just override the getCredentials() method in your AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
public function getCredentials($request)
{
$credentials = $request->only($this->loginUsername(), 'password');
return array_add($credentials, 'active', '1');
}
}
This will add the active = 1 constraint when trying to authenticate a user.
EDIT: If you want a separate error message like BrokenBinary says, then Laravel allows you to define a method called authenticated that is called after a user has been authenticated, but before the redirect, allowing you to do any post-login processing. So you could utilise this by checking if the authenticated user is active, and throw an exception or display an error message if not:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
public function authenticated(Request $request, User $user)
{
if ($user->active) {
return redirect()->intended($this->redirectPath());
} else {
// Raise exception, or redirect with error saying account is not active
}
}
}
Don’t forget to import the Request class and User model class.
I have now changed the auth middleware /app/Http/Middleware/Authenticate.php (added the block below the comment):
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('auth/login');
}
}
#logout if user not active
if($this->auth->check() && $this->auth->user()->active !== 1){
$this->auth->logout();
return redirect('auth/login')->withErrors('sorry, this user account is deactivated');
}
return $next($request);
}
It seems, it also logs out inactive users if they were already logged in.
I would add following first thing in postLogin() function.
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
if ($this->auth->validate(['email' => $request->email, 'password' => $request->password, 'active' => 0])) {
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors('Your account is Inactive or not verified');
}
active is a flag in user table. 0 = Inactive, 1 = active. so whole function would look like following..
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
if ($this->auth->validate(['email' => $request->email, 'password' => $request->password, 'active' => 0])) {
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors('Your account is Inactive or not verified');
}
$credentials = array('email' => $request->email, 'password' => $request->password);
if ($this->auth->attempt($credentials, $request->has('remember'))){
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => 'Incorrect email address or password',
]);
}
Solved: this link ( tutorial) will help you : https://medium.com/#mshanak/solved-tutorial-laravel-5-3-disable-enable-block-user-login-web-passport-oauth-4bfb74b0c810
step1:
add new field to the User table called ‘status’ (1:enabled, 0:disabed)
step2:
to block the web login , in app/Http/Controllers/Auth/LoginController.php add the follwoing function:
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(\Illuminate\Http\Request $request)
{
$credentials = $request->only($this->username(), ‘password’);
return array_add($credentials, ‘status’, ‘1’);
}
Step3:
to block the user when using passport authentication ( token ) , in the User.php model add the following function :
public function findForPassport($identifier) {
return User::orWhere(‘email’, $identifier)->where(‘status’, 1)->first();
}
Done :)
On Laravel 5.3.* update app/Http/Controllers/Auth/LoginController
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(\Illuminate\Http\Request $request)
{
$credentials = $request->only($this->username(), 'password');
return array_add($credentials, 'active', '1');
}
// your code here

How to run more logic after user registration in Laravel 5

I am using the default user registrar in Laravel 5. When the user registers there is some information stored in the session so after the user has been created I want to run some code to process the session data, store it and link it to the user. Would I just amend the create method in the registrar from this:
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
}
to this:
public function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
// do my other logic to process session data here
return $user;
}
Or is there a better way to do it?
You can use a model event, place this code in your model.
public static function boot()
{
static::created(function($model)
{
//do other logic here
});
}
http://laravel.com/docs/5.0/eloquent#model-events
You can also opt for a model observer:
<?php namespace App\Observers;
use Illuminate\Database\Eloquent\Model as Eloquent;
class UserObserver {
public function created(Eloquent $model)
{
//do other logic
}
}
You'll need a listener to this observer:
\App\User::observe(new \App\Observers\UserObserver);
You can place the listener in the routes.php file to test it.
Later on you can move the listener to a more appropriate location such as a ServiceProvider.
http://laravel.com/docs/5.0/eloquent#model-observers

Categories