php - Laravel using wrong table for registration and returns "SQLSTATE[42S22]: Column not found"
one text
Solution:
I just remember the medium article, which I've written 2 years ago. There I've created separate table for other users (like admins). I think that's similar to your task (at least for "config/auth.php" management), but anyway that was for older Laravel version projects, and specifically your question is little bit different.
So return back to your question, I'll suggest you to do these steps:
- Create new app/Models/Login.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class Login extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
}
- Change default app/Models/User.php (basically it will extend the "Model" instead of "Authenticable") and make that as a simple model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
protected $table = 'users';
protected $fillable = [
'name',
'email',
'password',
];
}
- This is the config/auth.php:
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'logins',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'logins',
],
'api' => [
'driver' => 'token',
'provider' => 'logins',
'hash' => false,
],
],
'providers' => [
'logins' => [
'driver' => 'eloquent',
'model' => App\Models\Login::class,
],
],
'passwords' => [
'logins' => [
'provider' => 'logins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
- Manually create a new database/migrations/202108200241_create_logins_table.php migration file, or run "php artisan make:migration create_logins_table":
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLoginsTable extends Migration
{
public function up()
{
Schema::create('logins', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('logins');
}
}
- This is the app/Http/Controllers/AuthController.php:
<?php
namespace App\Http\Controllers;
use App\Models\Login;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function register(Request $request)
{
$fields = $request->validate([
'name' => 'required|string',
'email' => 'required|string|unique:logins,email',
'password' => 'required|string|confirmed',
]);
Login::create([
'name' => $fields['name'],
'email' => $fields['email'],
'password' => bcrypt($fields['password']),
]);
return response()->json([
'success' => true,
'message' => "Successfully registered.",
], 201);
}
public function login(Request $request)
{
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string',
]);
$login = Login::where('email', $fields['email'])->first();
if(!$login || !Hash::check($fields['password'], $login->password)) {
return response()->json([
'success' => false,
'message' => "Bad credentials!",
], 401);
}
// FOR SANCTUM
// argument of "createToken" method could be anything
// $token = $login->createToken(config('app.key'))->plainTextToken;
return response()->json([
'success' => true,
'message' => "Successfully logged in.",
// 'token' => $token, // FOR SANCTUM
], 201);
}
// FOR SANCTUM
// public function logout(Request $request)
// {
// auth()->user()->tokens()->delete();
//
// return response()->json([
// 'success' => true,
// 'message' => "Logged out.",
// ], 201); // or 204
// }
}
- If you have already default Laravel auth system installed (I'll provide the commands for that below)
composer require laravel/ui
php artisan ui bootstrap
php artisan ui bootstrap --auth
npm i
npm run dev
npm run dev
Then you need to change app/Http/Controllers/Auth/RegisterController.php as well like this:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\Login;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::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:logins'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return Login::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
IMPORTANT
7. Now you can
change/add/remove all the fields you want in models;
migrations for Login & User entities;
controller's logic (RegisteredUserController@registered() method for your case) and returns;
Refresh caches by running "php artisan config:cache" (also "php artisan optimize" for Laravel v8).
Create a new "logins" table by running "php artisan migrate".
As you could assume, I've tested this with Web and SanctumAPI auth as well (which is in comments, and you can use them for later). So enjoy!