error in Laravel8: SQLSTATE[42S02]: Base table or view not found: 1146 Table - laravel-8

I have started a new project with Laravel 8.
I use the starter kit Laravel Breeze.
But I can't customize fields.
I have changed fields in the migration and Register Controller and User model.
here is my code:
migration file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class TblUsers extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tbl_users', function (Blueprint $table) {
$table->id();
$table->string('fullname');
$table->string('username');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('phone');
$table->string('organization_type');
$table->string('community_dev_auth_id');
$table->string('file_names');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tbl_users');
}
}
register controller file.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'fullname' => 'required|string|max:255',
'username' => 'required|string|max:255',
'email' => 'required|senter code heretring|email|max:255|unique:users',
'phone' => 'required|string|max:255',
'organization' => 'required|string|max:255',
'community' => 'required|string|max:255',
// 'phone' => 'required|string|max:255',
'password' => 'required|string|min:8',
]);
Auth::login($user = User::create([
'fullname' => $request->fullname,
'username' => $request->username,
'email' => $request->email,
'phone' => $request->phone,
'organization_type' => $request->organization,
'community_dev_auth_id' => $request->community,
'password' => Hash::make($request->password),
]));
event(new Registered($user));
return redirect(RouteServiceProvider::HOME);
}
}
user model file.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fullname',
'username',
'email',
'phone',
'organization',
'community',
'password',
];
/**
* 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',
];
}
I have run this project, but it returns this error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'ambulance_dubai.users' doesn't exist (SQL: select count(*) as
aggregate from users where email = asdf#sdf.df)

Since you are using a different table name for the user model you have to define it in your model. By default, Laravel will look for the plural name
of a model(users) if your model doesn't have a table property.
Add this to the user model:
protected $table='tbl_user';

first, you will check user table was migrate, the user table not to be migrated
use this command
php artisan migrate
Open your User Model
and add $table
class User extends Authenticatable {
protected $table = 'users';
}

Another cause could be that the validation has a different name for the table. For example, having the table tbl_users in the validation could exist an error and have:
'required|unique:tbl_user,email'.
The letter "s" is missing and the error would be thrown.

`
return [
//
'name' => 'required',
'image' => 'required',
'email' => 'required|unique:users,email',
'username' => 'required|unique:users,username',
'password' => 'required|min:8',
];
`
Where you see users should correspond to your table name in the database.
This is under validation.

Related

updating yii form record with uploaded file it throw an error if i don't attach the file again

when i create a new record in my yii form with uploaded file, it's working fine, but when i update ihave to attach the file again or else it will give error
here is my controller file, please tell me what is my mistake
my uploaded file is an image, what i want is to change one field let's say the date and keep the rest as is including the uploaded file, but if don't attach the file again it will give an error
<?php
namespace app\controllers;
use Yii;
use app\models\JetskiDamageSettlementAgreement;
use app\models\JetskiDamageSettlementAgreementSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
/**
* JetskiDamageSettlementAgreementController implements the CRUD actions for JetskiDamageSettlementAgreement model.
*/
class JetskiDamageSettlementAgreementController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all JetskiDamageSettlementAgreement models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new JetskiDamageSettlementAgreementSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single JetskiDamageSettlementAgreement model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new JetskiDamageSettlementAgreement model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new JetskiDamageSettlementAgreement();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
// get the instance of the uploaded file
$model->damage_image = UploadedFile::getInstance($model, 'damage_image');
$image_name = $model->customer_name.'.'.$model->damage_image->extension;
$image_path = 'attachments/' .$image_name;
$model->damage_image->saveAs($image_path);
$model->damage_image = $image_path;
$model->agreement_date = date ('y-m-d h:m:s');
$model->save();
return $this->redirect(['view', 'id' => $model->agreement_id]);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing JetskiDamageSettlementAgreement model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->damage_image = UploadedFile::getInstance($model, 'damage_image');
$image_name = $model->customer_name.'.'.$model->damage_image->extension;
$image_path = 'attachments/' .$image_name;
$model->damage_image->saveAs($image_path);
$model->damage_image = $image_path;
$model->save();
return $this->redirect(['view', 'id' => $model->agreement_id]);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing JetskiDamageSettlementAgreement model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the JetskiDamageSettlementAgreement model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return JetskiDamageSettlementAgreement the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = JetskiDamageSettlementAgreement::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
From what I understand you are getting the error because of your rules set to that model. In your model rules, this field for the file is set to be required for all scenarios.
One possible solution is to set the field to be required only on insert scenario and leave update scenario to be not required for the field. But this really depends on business logic that you need to satisfy.

Laravel Auth register user failing

I'm using Laravel's Auth scaffolding. When trying to register (create) a new user I'm getting the following error (from the logs):
Integrity constraint violation: 19 NOT NULL constraint failed: users.password
but password is part of $hidden array.
Here's my model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
const USER_FIRST_NAME_FIELD = "first_name";
const USER_LAST_NAME_FIELD = "last_name";
const USER_PREFERRED_NAME_FIELD = "preferred_name";
const USER_EMAIL_FIELD = "email";
const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
const USER_PASSWORD_FIELD = "password";
const USER_REMEMBER_TOKEN_FIELD = "remember_token";
const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
const USER_ACTIVE_FIELD = "active";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
self::USER_FIRST_NAME_FIELD,
self::USER_LAST_NAME_FIELD,
self::USER_PREFERRED_NAME_FIELD,
self::USER_EMAIL_FIELD,
self::USER_RECEIVE_NEWSLETTER_FIELD,
self::USER_ACTIVE_FIELD,
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
self::USER_PASSWORD_FIELD,
self::USER_REMEMBER_TOKEN_FIELD
];
}
and here's the create method in RegisterController:
protected function create(array $data) : User
{
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'preferred_name' => $data['preferred_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'receive_newsletter' => !isset($data['receive_newsletter']) || $data['receive_newsletter'] != 'on' ? 0 : 1,
]);
}
If I print out $data at the beginning of this method I can see that password is there.
Any suggestions?
Because password is not mass-assigned in fillable.
Use this:
protected $fillable = [
self::USER_FIRST_NAME_FIELD,
self::USER_LAST_NAME_FIELD,
self::USER_PREFERRED_NAME_FIELD,
self::USER_EMAIL_FIELD,
self::USER_PASSWORD_FIELD ,
self::USER_RECEIVE_NEWSLETTER_FIELD,
self::USER_ACTIVE_FIELD,
];
its because You haven't added password in protected $fillable,
Try updating fillable with password

Authentication using username instead of email laravel 5.2

Below is my code for 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;
//use App\Http\Requests\Request;
use Request;
use View;
use Hash;
use DB;
use Auth;
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 = '/home';
protected $redirectAfterLogout = '/login';
protected $username = 'user_name';
/**
* 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, [
'name' => 'required|max:255',
'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)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function showLogin()
{
if (Auth::check())
{
return redirect('/home');
}
else
{
return View::make('index');
}
}
public function doLogin()
{
//echo 'test';
$input = Request::all();
$pass = Hash::make($input['password']);
//print_r($input);exit;
//echo $input['username'];exit;
/*DB::table('admin_user')->insert(
['user_name' => $input['username'], 'password' => $pass]
);*/
if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
return redirect('/home');
//return View::make('home');
}
else
{
return redirect('/');
}
}
public function doLogout()
{
Auth::logout();
return redirect('/');
}
}
Below is my Route Code
Route::get('/',array('uses'=>'Auth\AuthController#showLogin') );
Route::post('/login',array('uses'=>'Auth\AuthController#doLogin'));
//Route::get('/login',array('uses'=>'Login#showLogin') );
Route::group(['middleware' => ['web', 'auth.basic']], function(){
Route::get('/home',['uses'=>'Home#getHome']);
Route::get('/logout',array('uses'=>'Auth\AuthController#doLogout') );
});
i am using user name instead of email id for Auth but below error is shown
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in
'where clause' (SQL: select * from admin_user where email = admin
limit 1)
below is my kernal.php code
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
please help me how can i do login with username .
Thanks in advance.
Update:
Add the auth middleware to specific route
Route::group(['middleware' => ['web']], function(){
Route::get('/',array('uses'=>'Auth\AuthController#showLogin') );
Route::post('/login',array('uses'=>'Auth\AuthController#doLogin'));
Route::get('/home',['uses'=>'Home#getHome'])->middleware('auth');//update
Route::get('/logout',array('uses'=>'Auth\AuthController#doLogout') );
});
To redirect to intended page after login replace your doLogin() function with following:
public function doLogin()
{
$input = Request::all();
$pass = Hash::make($input['password']);
if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
return redirect()->intended('/home');//This line is changed
}
else
{
return redirect('/');
}
}
Explaination:
intended() method redirects the user to the previous page, from where the user is redirected to login page. It expects a default route as a parameter, where user will be sent if he has came here directly.
Update 2:
add doLogout in your AuthController's constructor:
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'doLogout']);
}
You can simply override $username in AuthController by writing protected $username = 'username'.

No role detected by BjyAuthorize when login

I am working with ZF2, Doctrine ORM and BjyAuthorize.
The problem is that when I got logged in the method getRoles of the identity returns empty.
class User implements UserInterface, ProviderInterface{
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Application\Entity\Role", inversedBy="user")
* #ORM\JoinTable(name="user_role_linker",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="role_id", referencedColumnName="id")
* }
* )
*/
protected $roles;
public function __construct() {
$this->roles = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addRole(\Application\Entity\Role $role) {
$this->roles[] = $role;
return $this;
}
/**
* Remove role
*
* #param \Application\Entity\Role $role
*/
public function removeRole(\Application\Entity\Role $role) {
$this->roles->removeElement($role);
}
/**
* Get role
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getRoles() {
return $this->roles->getValues();
}
}
In the other hand, if I get the entity in the controller and I use getRoles, I get the values without any problem.
Could you please tell me which one could be the problem?
This is my zfc-user-doctrine-orm-global:
<?php
return array(
'doctrine' => array(
'driver' => array(
// overriding zfc-user-doctrine-orm's config
'zfcuser_entity' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'paths' => 'module\Application\src\Application\Entity',
),
'orm_default' => array(
'drivers' => array(
'Application' => 'zfcuser_entity',
),
),
),
),
'zfcuser' => array(
// telling ZfcUser to use our own class
'user_entity_class' => '\Application\Entity\User',
// telling ZfcUserDoctrineORM to skip the entities it defines
'enable_default_entities' => false,
),
'bjyauthorize' => array(
// Using the authentication identity provider, which basically reads the roles from the auth service's identity
'identity_provider' => 'BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider',
'role_providers' => array(
// using an object repository (entity repository) to load all roles into our ACL
'BjyAuthorize\Provider\Role\ObjectRepositoryProvider' => array(
'object_manager' => 'doctrine.entitymanager.orm_default',
'role_entity_class' => 'Application\Entity\Role',
),
),
),
);
Do you have your roles defined in 'role' table, and userid <-> roleid in user_role_linker table?

Can't authenticate with different table

I've changed the auth.php file in order to authenticate my users according to authors table. But I keep getting No account for you when I'm running test route.
auth.php
<?php
return array(
'driver' => 'eloquent',
'model' => 'Author',
'table' => 'authors',
'reminder' => array(
'email' => 'emails.auth.reminder', 'table' => 'password_reminders',
),
);
routes.php
Route::get('test', function() {
$credentials = array('username' => 'giannis',
'password' => Hash::make('giannis'));
if (Auth::attempt($credentials)) {
return "You are a user.";
}
return "No account for you";
});
AuthorsTableSeeder.php
<?php
class AuthorsTableSeeder extends Seeder {
public function run()
{
// Uncomment the below to wipe the table clean before populating
DB::table('authors')->delete();
$authors = array(
[
'username' => 'giannis',
'password' => Hash::make('giannis'),
'name' => 'giannis',
'lastname' => 'christofakis'],
[
'username' => 'antonis',
'password' => Hash::make('antonis'),
'name' => 'antonis',
'lastname' => 'antonopoulos']
);
// Uncomment the below to run the seeder
DB::table('authors')->insert($authors);
}
}
Addendum
I saw in another post that you have to implement the UserInterface RemindableInterface interfaces. But the result was the same.
Author.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Author extends Eloquent implements UserInterface, RemindableInterface {
protected $guarded = array();
public static $rules = array();
public function posts() {
return $this->hasMany('Post');
}
/**
* 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 "giannis#hotmail.com";
}
}
You don't need to Hash your password when you are using Auth::attempt(); so remove Hash::make from routes
Route::get('test', function() {
$credentials = array('username' => 'giannis',
'password' => 'giannis');
if (Auth::attempt($credentials)) {
return "You are a user.";
}
return "No account for you";
});
and it will work like a charm!