using laravel 4 I am trying to add 'active' column to my database to check if the user is active and is not suspended , here is my migration users table.
public function up()
{
//
Schema::create(
'users',
function (Blueprint $table) {
$table->increments('id');
$table->string('email', 300);
$table->string('password', 60);
$table->boolean('active'); // check this one
$table->string('first_name', 100);
$table->string('last_name', 100);
$table->string('address', 250)->nullable();
$table->string('city', 100)->nullable();
$table->string('state', 2)->nullable();
$table->string('zip', 5)->nullable();
$table->string('phone', 10)->nullable();
$table->timestamps();
}
);
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::drop('users');
}
could you help me if I use $table->boolean('active'); // check this one
*is this the right way to do it? so I can use the Auth class like this to check if the user is active or not? *
$is_active = Auth::user()->active;
if (!$is_active == 1)
{
echo "Account not activated";
}
You can do it the way you have mentioned but the Laravel way to do this exists
if (Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1)))
{
// The user is active, not suspended, and exists.
}
Read : Laravel\Docs\Authentication
Just my 2 bit : The way are building you database is not advised. You should keep your user login information (email, password & active) in users table and others in a separate user_profile table. Later you can use eloquent to map relations.
Related
I want to save the datetime of last interaction of a user with the application inside the user table.
I'm using Laravel 8.
I added a column in users table (last_interaction):
Schema::create('users', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->integer('id', true);
$table->string('firstname');
$table->string('lastname');
$table->string('username', 192);
$table->string('email', 192);
$table->string('password');
$table->string('avatar')->nullable();
$table->string('phone', 192);
$table->integer('role_id');
$table->boolean('statut')->default(1);
$table->datetime('last_interaction'); //The column where to save the datetime of last interaction
$table->timestamps(6);
$table->softDeletes();
});
Is it possible to update the users table with each request done! or should i do it on login only (for Optimisations) ?
You can make new middleware with this command php artisan make:middleware LastInteraction
App\Http\Middleware\LastInteraction.php:
public function handle(Request $request, Closure $next)
{
if (Auth::check()) {
$user = Auth::user();
$user->last_interacted = Carbon::now();
$user->save();
}
return $next($request);
}
This will set a field of last_interacted to the current time given this field exists in your migration. If it doesn't exist create one.
App\Http\Kernel.php
protected $middleware = [
(...)
\App\Http\Middleware\LastInteraction::class,
];
This will register the middleware to be applied globally to each route.
I am making a project in Php Laravel that allows the logged in user to rent a book, but if the logged in user has rented 1 book, I am trying to prevent different book rentals, but what I am doing does not work, where is my mistake?
1-"This is my code where i rent a book" :
public $user_id;
public $kitap_id;
public $AlimTarihi;
public $TeslimTarihi;
public $durum;
public function kirala($kitap_id)
{
if(Auth::check())
{
if(Kira::where('user_id',Auth::user()->id)->where('durum',"Edilmedi"))
{
session()->flash('message','There is a book you are renting.');
return redirect('/user/dashboard');
}
else
{
$kira = new Kira();
$kira->user_id = Auth::user()->id;
$kira->kitap_id = $kitap_id;
$kira->AlimTarihi = Carbon::now();
$kira->TeslimTarihi = Carbon::now()->addDays(7);
$kira->durum = 'Edilmedi';
$kitaplar = Kitaplar::find($kitap_id);
$kitaplar->kiraliMi = 1;
$kitaplar->save();
$kira->save();
session()->flash('message','book is rented.');
return redirect('/user/dashboard');
}
}
else
{
return redirect()->route('login');
}
}
2- "Rent table" :
Schema::create('kiras', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->unsigned()->nullable();
$table->bigInteger('kitap_id')->unsigned()->nullable();
$table->timestamp('AlimTarihi')->nullable();
$table->timestamp('TeslimTarihi')->nullable();
$table->enum('durum',['Edildi','Edilmedi'])->default('Edilmedi');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('kitap_id')->references('id')->on('kitaplars')->onDelete('cascade');
});
3- "Book table" :
Schema::create('kitaplars', function (Blueprint $table) {
$table->id();
$table->string('KitapAdi');
$table->BigInteger('BarkodNo');
$table->BigInteger('SayfaSayisi');
$table->decimal('SatisFiyati')->nullable();
$table->string('image')->nullable();
$table->text('images')->nullable();
$table->bigInteger('kategori_id')->unsigned()->nullable();
$table->bigInteger('yazar_id')->unsigned()->nullable();
$table->boolean('kiraliMi');
$table->timestamps();
$table->foreign('kategori_id')->references('id')->on('kategoris')->onDelete('cascade');
$table->foreign('yazar_id')->references('id')->on('yazarlars')->onDelete('cascade');
});
4- "User table" :
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('lastName')->nullable();
$table->BigInteger('Yasi')->nullable();
$table->string('Adres')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->string('profile_photo_path', 2048)->nullable();
$table->string('utype')->default('USR')->comment('ADM for Admin and USR for User or Customer');
$table->timestamps();
});
I believe your initial if-check isn't doing what you expect. This line:
if(Kira::where('user_id',Auth::user()->id)->where('durum',"Edilmedi"))
is an incomplete builder object, so will always return true. I suggest completing the query with something along the lines of:
if(isset(Kira::where('user_id',Auth::user()->id)->where('durum',"Edilmedi")->first()))
or if you have allowed multiples rented out in some previous instance, something like this might work as you wish:
if(Kira::where('user_id',Auth::user()->id)->where('durum',"Edilmedi")->count())
I am beginner in Laravel and php.
I use in my project Laravel 6.
I have this migrations:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->char('enable', 1)->default(0);
$table->rememberToken();
$table->timestamps();
});
How to change Laravel's default login so that it allows the login of a user who has enable = 1 (enable = 0 - we do not allow, similar to those with an incorrect password)
According to Laravel document on Manually Authenticating Users, you can use this code to authenticate users with enabled field set to true only.
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password, 'enabled' => 1])) {
// The user is active, not suspended, and exists.
}
I have this migrations:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->boolean('enable')->default(0);
$table->string('name', 120)->nullable();
$table->string('surname', 120)->nullable();
$table->string('email', 120)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->bigInteger('counter')->default(0);
$table->string('url_address', 160);
$table->string('ip', 25)->nullable();
$table->boolean('isCompany')->default(0);
$table->boolean('isMailing')->default(0);
$table->text('content')->nullable();
$table->string('nip1', 12)->nullable();
$table->string('business1', 120)->nullable();
$table->string('phone1', 60)->nullable();
$table->string('street1', 150)->nullable();
$table->string('number1', 8)->nullable();
$table->string('postal_code1', 12)->nullable();
$table->string('city1', 100)->nullable();
$table->bigInteger('country_id1')->default(0);
$table->bigInteger('provincial_id1')->default(0);
$table->string('nip2', 12)->nullable();
$table->string('business2', 120)->nullable();
$table->string('phone2', 60)->nullable();
$table->string('street2', 150)->nullable();
$table->string('number2', 8)->nullable();
$table->string('postal_code2', 12)->nullable();
$table->string('city2', 100)->nullable();
$table->bigInteger('country_id2')->default(0);
$table->bigInteger('provincial_id2')->default(0);
$table->string('nip3', 12)->nullable();
$table->string('business3', 120)->nullable();
$table->string('phone3', 60)->nullable();
$table->string('street3', 150)->nullable();
$table->string('number3', 8)->nullable();
$table->string('postal_code3', 12)->nullable();
$table->string('city3', 100)->nullable();
$table->bigInteger('country_id3')->default(0);
$table->bigInteger('provincial_id3')->default(0);
$table->decimal('cash', 9, 2)->default(0);
$table->decimal('lng', 10, 8)->default(0);
$table->decimal('lat', 10, 8)->default(0);
$table->boolean('enable_map')->default(0);
$table->rememberToken();
$table->timestamps();
$table->engine = "InnoDB";
});
I have 2 questions in connection with logging in to Laravel:
I would like to be able to log in only if the user has enable = 1
The parameter enable is the default value of 0. After clicking the activation link in the mail I would like to change enable = 0 on enable = 1
How can I do this?
When calling the attempt() method you can pass an array of credentials that can be used.
You can do as mentioned previously and create your own controllers, but if you're using the auth scaffolding that comes with laravel (This includes auth:make and the classes in app/Http/Controllers/Auth) you can simply edit the file:
app/Http/Controllers/Auth/LoginController.php
In here you want to override the credentials method by adding the following:
protected function credentials(Request $request)
{
return array_merge($request->only($this->username(), 'password'), ['active' => 1]);
}
This means that when the rest of the code kicks in automatically, it'll make the credentails array look something like:
array(
'username' => 'theusername',
'password' => 'thepassword',
'active' => 1
)
It was mentioned previously that you should cast your attribute to a boolean, but this is not true. Laravel migrations create a tiny int column instead of a boolean, and the casting only works when dealing with models. Since this array is used to generate where conditions on the DB query, casting won't work as the value in the DB will be 1 not true.
For that you have to make custom login controller and handle this situation.
I am mentioning this in detail check me below given steps.
Update your routes/web.php
Route::get('/', function () {
return redirect(route('login'));
});
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/authenticate', 'LoginController#authenticate')->name('authenticate');
Route::get('/logout', '\App\Http\Controllers\Auth\LoginController#logout');
Create app/Http/Controllers/LoginController.php
and add this method into this controller
/**
* Handle an authentication attempt.
*
* #param \Illuminate\Http\Request $request
*
* #return Response
*/
public function authenticate(Request $request)
{
//ADD VALIDATION CODE HERE
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
So I have mentioned in above method "//ADD VALIDATION CODE HERE
" at that place you have to validate request and make query to check that user is enabled or not.
I hope this will work for you.
You will have to override the default controllers and routes.
First remove the auth routes as you are going to create them yourself.
Then define your controllers.
For the login part you can create your own Login Controller and in there make your own login attempt which is what Laravel uses. There you can add your desired attribute validations like this.
public function login(Request $request)
{
//Validate your form data here
$request->validate([
'email' => ['required', 'string'],
'password' => ['required', 'string'],
]);
//Create your own login attempt here
$login_atempt = Auth::attempt([
'email' => $request->email,
'password' => $request->password,
'enabled' => true //or 1 , I recommend you to cast your attribute to boolean in your model
], $request->filled('remember'));
if ($login_atempt) {
$request->session()->regenerate();
return redirect()->route('home'); //Your home screen route after successful login
}
//using custom validation message as Laravel does
throw ValidationException::withMessages([
'email' => [trans('auth.failed')],
]);
}
also add a simple method to call the login form.
public function showLoginForm()
{
return view('auth.login');
}
Then your routes (I named my controller, UserLoginController)
Route::group(['middleware' => 'guest'], function () {
Route::get('/login', 'UserLoginController#showLoginForm')->name('login.index');
Route::post('/login', 'UserLoginController#login')->name('login');
});
For the second question Laravel documentation states
After an email address is verified, the user will automatically be redirected to /home. You can customize the post verification redirect location by defining a redirectTo method or property on the VerificationController:
protected $redirectTo = '/dashboard';
So you can make your own controller that handles that enable attribute change and redirection.
To finish, make sure you manually add the auth routes you need.
I am implementing a social authentication on my website with laravel 5.
I successfully logged in a couple of users but now for some very strange reasons it doesn't work anymore..
When I try to log in a new user I have this error coming up:
QueryException in Connection.php line 624:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_email_unique' (SQL: insert into `users` (`name`, `profile_picture`, `facebook_id`) values (Hwan, https://graph.facebook.com/v2.4/1701160536770162/picture1701160536770162type=normal, ?))
But this user has never been registered in the DB before !!
I tried with other users, all the same...
But if I remove an existing FB user from the DB and try again, it works !!
Here is my controller:
class AccountController extends Controller {
/**
* Redirect the app to the social provider
*
* #return SNS token and user data
*/
public function redirectToProvider($provider) {
return Socialize::with($provider)->redirect();
}
/**
* Callback handler
*
* #return redirect to index
*/
public function handleProviderCallback($provider) {
$user = Socialize::with($provider)->user();
// get the sns user data
$id = $user->getId();
$name = $user->getName();
$avatar = $user->getAvatar();
// get the user provider id form the DB
$users = DB::table('users')->where($provider.'_id', $id)->get();
// check if the record exists
if(empty($users)){
DB::table('users')->insert(
['name' => $name,'profile_picture' => $avatar,$provider.'_id' => $id]
);
$users = DB::table('users')->where($provider.'_id', $id)->get();
}
foreach ($users as $user)
{
$userID = $user->id;
}
Auth::loginUsingId($userID);
{
return redirect()->to('home');
}
}
}
And my routes:
Route::get('connect/{provider}', 'AccountController#redirectToProvider');
Route::get('account/{provider}', 'AccountController#handleProviderCallback');
And my user schema:
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('profile_picture');
$table->text('facebook_id');
$table->rememberToken();
$table->timestamps();
});
Any help is greatly appreciated
Thank you
You have a unique constraint on your email field but you do not appear to be inserting an email address. After one user is inserted without an email address, no other users can be signed up without an email address.
You will not be able to have two empty strings in the email column of your database.