How Can I dynamicaly change users table name? - php

My app has two types of users : teachers and parents. When you log in you have to specify what type you are.
I change the table name in user's constructor function :
public function __construct()
{
parent::__construct();
if(self::$userType === null)
{
self::$userType = request('user_type');
switch(self::$userType)
{
case 'teacher':
self::$userType = 'teachers';
$this->table = self::$userType;
break;
default:
self::$userType = 'procreators';
$this->table = self::$userType;
break;
}
}
This code works. However I decided to change failed authentication behavior in AuthenticatesUsers trait. This is it :
$password = bcrypt($request->input('password'));
$username = $request->input('name');
if(!User::where('name', 'LIKE', $username)->exists())
{
throw ValidationException::withMessages([
$this->username() => ['User login does not exist'],
]);
}
else if(!User::where('password', 'LIKE', $password)->exists())
{
throw ValidationException::withMessages([
'password' => ['invalid password'],
]);
}
When I type in wrong password I get an error that says "users" table does not exists. So it means it still uses the old name 'users'. I don't know why. How can I dynamically change the table's name? Apparently this code in constructor method is not enough.

Maybe static instead of self? If that isn't it, what is request('user_type') returning?
static::$userType = 'teachers';

Schema::rename('old_table_name', 'teacher');

Related

How to update in one to one relation in laravel?

In my user model, I have the following code
public function profile()
{
return $this->hasOne(UserProfile::class);
}
In profile model,
public function user()
{
return $this->belongsTo(User::class);
}
The create method is working, But when I try to update the profile with following code, It is creating a new profile and doesn’t update the profile information.
$profile = new UserProfile();
$profile->dob = '1999-03-20';
$profile->bio = 'A professional programmer.';
$profile->facebook = 'http://facebook.com/test/1';
$profile->github = 'http://github.com/test/1';
$profile->twitter = 'http://twitter.com/test/1';
$user = User::find($userId);
$res = $user->profile()->save($profile);
What is the correct method to update in One to One Relationship ?
I fixed it using push method. Here is the code.
$user = User::find($userId);
$user->name = "Alen";
$user->profile->dob = '1999-03-20';
$user->profile->bio = 'A professional programmer.';
$user->profile->facebook = 'http://facebook.com/test/1';
$user->profile->github = 'http://github.com/test/1';
$user->profile->twitter = 'http://twitter.com/test/1';
$user->push();
You're doing right, however i could suggest a little improvement
You may use the following
$user = User::with('profile')->findOrFail($userId);
if ($user->profile === null)
{
$profile = new UserProfile(['attr' => 'value', ....]);
$user->profile()->save($profile);
}
else
{
$user->profile()->update(['attr' => 'value', ....]);
}
you are using save method to save new record. use update query
//controller
$userObj=new User();
if(!empty($userId) && $userId!=null){
$userObj->updateByUserId($userId,[
'dob' = '1999-03-20';
'bio' = 'A professional programmer.';
'facebook' = 'http://facebook.com/test/1';
'github' = 'http://github.com/test/1';
'twitter' = 'http://twitter.com/test/1';
]);
}
//model
function updateByUserId($userId,$updateArray){
return $this->where('user_id',$userId)->update($updateArray);
}

Call to a member function save() on null

I am using the following code
public function show()
{
$id = Auth::user()->id;
$usuario = User::find($id);
$mascotin = Mascota::all();
$mascota = Mascota::find($id);
$mascota->save();
$cant_mascota = Mascota::count();
$cant_pregunta = Pregunta::count();
return view('usuario.show',[
'usuario' => $usuario,
'mascotin' => $mascotin,
'mascota' => $mascota,
'cant_mascota' => $cant_mascota,
'cant_pregunta' => $cant_pregunta,
]);
}
It gives me this error
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR).Call to a member function save() on null
User Model
public function mascotas(){
return $this->hasMany('App\Mascota','user_id', 'id');
}
Mascota Model
public function usuario()
{
return $this->belongsTo('App\User', 'id','user_id');
}
Route
Route::get('/home', 'UserController#show')->name('home');
Hope you guys can help me, I'm new in laravel and I have like 1 day tring to solve this problem
$usuario = Auth::user();
$id = $usuario->id; // you already have user from Auth or Request, does not need to request database again
$mascotin = Mascota::all();
$mascota = $mascotin->find($id); // you can search in collection
//if you want to create Mascotin if it doesn't exists use Mascota::firstOrCreate(['id' => $id]);
if(!$mascota){
throw new \Exception('Mascota not found', 404); //if $mascota is mandatory
}
$mascota->save(); // this does not have place here unless you are changing $mascota before that
$cant_mascota = $mascotin->count();
$cant_pregunta = Pregunta::count();
Also you should add auth middleware to this route. Only logged users should see it.
I am not sure what "Mascota" means (it will be good to use english when you share your code) but it is not good to have the same id as user. Better use relationships.

Yii2; code running in "else" block first, and then running code before "if" block?

I'm completely lost as to why this is happening, and it happens about 50% of the time.
I have a check to see if a user exists by email and last name, and if they do, run some code. If the user doesn't exist, then create the user, and then run some code.
I've done various testing with dummy data, and even if a user doesn't exist, it first creates them, but then runs the code in the "if" block.
Here's what I have.
if (User::existsByEmailAndLastName($params->email, $params->lastName)) {
var_dump('user already exists');
} else {
User::createNew($params);
var_dump("Creating a new user...");
}
And here are the respective methods:
public static function existsByEmailAndLastName($email, $lastName) {
return User::find()->where([
'email' => $email,
])->andWhere([
'last_name' => $lastName
])->one();
}
public static function createNew($params) {
$user = new User;
$user->first_name = $params->firstName;
$user->last_name = $params->lastName;
$user->email = $params->email;
$user->address = $params->address;
$user->address_2 = $params->address_2;
$user->city = $params->city;
$user->province = $params->province;
$user->country = $params->country;
$user->phone = $params->phone;
$user->postal_code = $params->postal_code;
return $user->insert();
}
I've tried flushing the cache. I've tried it with raw SQL queries using Yii::$app->db->createCommand(), but nothing seems to be working. I'm totally stumped.
Does anyone know why it would first create the user, and then do the check in the if statement?
Editing with controller code:
public function actionComplete()
{
if (Yii::$app->basket->isEmpty()) {
return $this->redirect('basket', 302);
}
$guest = Yii::$app->request->get('guest');
$params = new CompletePaymentForm;
$post = Yii::$app->request->post();
if ($this->userInfo || $guest) {
if ($params->load($post) && $params->validate()) {
if (!User::isEmailValid($params->email)) {
throw new UserException('Please provide a valid email.');
}
if (!User::existsByEmailAndLastName($params->email, $params->lastName)) {
User::createNew($params);
echo "creating new user";
} else {
echo "user already exists";
}
}
return $this->render('complete', [
'model' => $completeDonationForm
]);
}
return $this->render('complete-login-or-guest');
}
Here's the answer after multiple tries:
Passing an 'ajaxParam' parameters with the ActiveForm widget to define the name of the GET parameter that will be sent if the request is an ajax request. I named my parameter "ajax".
Here's what the beginning of the ActiveForm looks like:
$form = ActiveForm::begin([
'id' => 'complete-form',
'ajaxParam' => 'ajax'
])
And then I added this check in my controller:
if (Yii::$app->request->get('ajax') || Yii::$app->request->isAjax) {
return false;
}
It was an ajax issue, so thanks a bunch to Yupik for pointing me towards it (accepting his answer since it lead me here).
You can put validation like below in your model:
public function rules() { return [ [['email'], 'functionName'], [['lastname'], 'functionforlastName'], ];}
public function functionName($attribute, $params) {
$usercheck=User::find()->where(['email' => $email])->one();
if($usercheck)
{
$this->addError($attribute, 'Email already exists!');
}
}
and create/apply same function for lastname.
put in form fields email and lastname => ['enableAjaxValidation' => true]
In Create function in controller
use yii\web\Response;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post()))
{
//place your code here
}
Add 'enableAjaxValidation' => false to your ActiveForm params in view. It happens because yii sends request to your action to validate this model, but it's not handled before your if statement.

Laravel Checking If a Record Exists

I am new to Laravel. How do I find if a record exists?
$user = User::where('email', '=', Input::get('email'));
What can I do here to see if $user has a record?
It depends if you want to work with the user afterwards or only check if one exists.
If you want to use the user object if it exists:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
And if you only want to check
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
Or even nicer
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
if (User::where('email', Input::get('email'))->exists()) {
// exists
}
In laravel eloquent, has default exists() method, refer followed example.
if (User::where('id', $user_id )->exists()) {
// your code...
}
One of the best solution is to use the firstOrNew or firstOrCreate method. The documentation has more details on both.
if($user->isEmpty()){
// has no records
}
Eloquent uses collections.
See the following link: https://laravel.com/docs/5.4/eloquent-collections
Laravel 5.6.26v
to find the existing record through primary key ( email or id )
$user = DB::table('users')->where('email',$email)->first();
then
if(!$user){
//user is not found
}
if($user){
// user found
}
include " use DB " and table name user become plural using the above query like user to users
if (User::where('email', 'user#email.com')->first()) {
// It exists
} else {
// It does not exist
}
Use first(), not count() if you only need to check for existence.
first() is faster because it checks for a single match whereas count() counts all matches.
It is a bit late but it might help someone who is trying to use User::find()->exists() for record existence as Laravel shows different behavior for find() and where() methods. Considering email as your primary key let's examine the situation.
$result = User::find($email)->exists();
If a user record with that email exists then it will return true. However the confusing thing is that if no user with that email exists then it will throw an error. i.e
Call to a member function exists() on null.
But the case is different for where() thing.
$result = User::where("email", $email)->exists();
The above clause will give true if record exists and false if record doesn't exists. So always try to use where() for record existence and not find() to avoid NULL error.
This will check if requested email exist in the user table:
if (User::where('email', $request->email)->exists()) {
//email exists in user table
}
In your Controller
$this->validate($request, [
'email' => 'required|unique:user|email',
]);
In your View - Display Already Exist Message
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over.
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
would work with try/catch
->get() would still return an empty array
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
Simple, comfortable and understandable with Validator
class CustomerController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:customers',
'phone' => 'required|string|max:255|unique:customers',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
return response(['errors' => $validator->errors()->all()], 422);
}
I solved this, using empty() function:
$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
User::destroy($user->id);
you have seen plenty of solution, but magical checking syntax can be like,
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
it will automatically raise an exception with response 404, when not found any related models Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The fingernail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
Ref: https://laravel.com/docs/5.8/eloquent#retrieving-single-models
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
This will check if particular email address exist in the table:
if (isset(User::where('email', Input::get('email'))->value('email')))
{
// Input::get('email') exist in the table
}
Shortest working options:
// if you need to do something with the user
if ($user = User::whereEmail(Input::get('email'))->first()) {
// ...
}
// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
can be written as
if (User::where('email', '=', Input::get('email'))->first() === null) {
// user doesn't exist
}
This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.
I think below way is the simplest way to achieving same :
$user = User::where('email', '=', $request->input('email'))->first();
if ($user) {
// user exist!
}else{
// user does not exist
}
Created below method (for myself) to check if the given record id exists on Db table or not.
private function isModelRecordExist($model, $recordId)
{
if (!$recordId) return false;
$count = $model->where(['id' => $recordId])->count();
return $count ? true : false;
}
// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);
Home It helps!
The Easiest Way to do
public function update(Request $request, $id)
{
$coupon = Coupon::where('name','=',$request->name)->first();
if($coupon->id != $id){
$validatedData = $request->validate([
'discount' => 'required',
'name' => 'required|unique:coupons|max:255',
]);
}
$requestData = $request->all();
$coupon = Coupon::findOrFail($id);
$coupon->update($requestData);
return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
}
Laravel 6 or on the top: Write the table name, then give where clause condition for instance where('id', $request->id)
public function store(Request $request)
{
$target = DB:: table('categories')
->where('title', $request->name)
->get()->first();
if ($target === null) { // do what ever you need to do
$cat = new Category();
$cat->title = $request->input('name');
$cat->parent_id = $request->input('parent_id');
$cat->user_id=auth()->user()->id;
$cat->save();
return redirect(route('cats.app'))->with('success', 'App created successfully.');
}else{ // match found
return redirect(route('cats.app'))->with('error', 'App already exists.');
}
}
If you want to insert a record in the database if a record with the same email not exists then you can do as follows:
$user = User::updateOrCreate(
['email' => Input::get('email')],
['first_name' => 'Test', 'last_name' => 'Test']
);
The updateOrCreate method's first argument lists the column(s) that uniquely identify records within the associated table while the second argument consists of the values to insert or update.
You can check out the docs here: Laravel upserts doc
You can use laravel validation if you want to insert a unique record:
$validated = $request->validate([
'title' => 'required|unique:usersTable,emailAddress|max:255',
]);
But also you can use these ways:
1:
if (User::where('email', $request->email)->exists())
{
// object exists
} else {
// object not found
}
2:
$user = User::where('email', $request->email)->first();
if ($user)
{
// object exists
} else {
// object not found
}
3:
$user = User::where('email', $request->email)->first();
if ($user->isNotEmpty())
{
// object exists
} else {
// object not found
}
4:
$user = User::where('email', $request->email)->firstOrCreate([
'email' => 'email'
],$request->all());
$userCnt = User::where("id",1)->count();
if( $userCnt ==0 ){
//////////record not exists
}else{
//////////record exists
}
Note :: Where condition according your requirements.
Simply use this one to get true or false
$user = User::where('email', '=', Input::get('email'))->exists();
if you want $user with result you can use this one,
$user = User::where('email', '=', Input::get('email'))->get();
and check result like this,
if(count($user)>0){}
Other wise you can use like this one,
$user = User::where('email', '=', Input::get('email'));
if($user->exists()){
$user = $user->get();
}
The efficient way to check if the record exists you must use is_null method to check against the query.
The code below might be helpful:
$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
//user does not exist...
}else{
//user exists...
}
It's simple to get to know if there are any records or not
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";

Yii2 RBAC DbManager error Call to a member function getRole() on null

I've set up the database etc by having implemented SQL code to set up the tables and the rbac/init script to fill out the roles / permissions.
I have an assign() at user creation but I keep receiving this error on the getRole():
yii\base\ErrorException Call to a member function getRole() on null
public function addUser()
{
if($this->validate()) {
$user = new User();
$auth_key = Yii::$app->getSecurity()->generateRandomString(32);
$this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);
$user->email = $this->email;
$user->password = $this->password;
$user->active = $this->active;
$user->firstname = $this->firstname;
$user->lastname = $this->lastname;
// $user->nickname = $this->nickname;
$user->datecreated = time();
$user->auth_key = $auth_key;
$user->save(false);
$auth = Yii::$app->authManager;
$authorRole = $auth->getRole($this->role);
$auth->assign($authorRole, $user->getId());
return $user;
}else{
return false;
}
}
the $role variable is passed through $_POST along with the other user attributes.
Please help. Thanks.
You've gone the wrong way about it.
The issue here seems to be that Yii::$app->authManager is not set when it should be. This probably means that your main.php configuration file does not contain the correct information.
It should contain the following component:
return [
// ...
'components' => [
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
// ...
],
];
(http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#configuring-rbac-manager)
In the example from the link above PhpManager is used but in your case you will want to use yii\rbac\DbManager
Doing it this way means that you will only have one loaded manager and will also unlock all action filtering options.
I seem to have fixed this by replacing
$auth = Yii::$app->authManager;
with
$auth = new DbManager;
Let me know if this is the wrong way to go about it!

Categories