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.
Related
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 making a small test web store in Laravel. Tried to edit user profile. There are so many fields:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('phone')->nullable();
$table->string('img')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
But I'm trying to change only 3 of them, and an error is displayed that others do not have a default value, and why does it even touch other fields? Or am I doing something wrong?
public function user_edit(Request $request, User $user){
$user->name = $request->name?$request->name:Auth::user()->name;
$user->email = $request->email?$request->email:Auth::user()->email;
$user->phone = $request->phone?$request->phone:(Auth::user()->phone?Auth::user()->phone:NULL);
$user->save();
return redirect()->back();
}
Just use :
$user->update();
$user->save(); will perform an INSERT
EDIT
The error is maybe because your $user in params is not defined or not found.
So instead of updating your User instance when you use ->save(), it tries to create a new one.
You can't inject the authentificated User like this, as mentionned, you can use :
$user = auth()->user();
$user->name = $request->name?$request->name:$user->name;
$user->email = $request->email?$request->email : $user->email;
$user->phone = $request->phone?$request->phone : ($user->phone?$user->phone:NULL);
$user->save();
Not the best honestly but can explain the error.
Also, I have not specified user_id anywhere. So, at the top I added:
$user=Auth::user();
And it worked.
public function user_edit(Request $request, User $user){
$user->name = $request->name?$request->name:Auth::user()->name;
$user->email = $request->email?$request->email:Auth::user()->email;
$user->phone = $request->phone?$request->phone:(Auth::user()->phone?Auth::user()->phone:NULL);
$user->password = $request->password?$request->password:Auth::user()->password;
$user->save();
return redirect()->back();
}
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 successfully implement a payment gateway on my Laravel Application
But I get this response from the payment
public function handleGatewayCallback()
{
$paymentDetails = Payant::getPaymentData();
dd($paymentDetails);
}
What I am trying to is to save some of the response to the user database, but I am unable to achieve this. I tried doing it this way
public function handleGatewayCallback(Request $request)
{
$paymentDetails = Payant::getPaymentData();
// dd($paymentDetails);
$user = User::find(Auth::id());
$user->sub_paid_at = $request->paid_at;
$user->role = $request->planObject['name'];
$user->save();
}
It returned this error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'sub_paid_at' cannot be null (SQL: update users set sub_paid_at = ?, users.updated_at = 2019-12-14 07:27:45 where id = 3)
UPDATE
This is my user database Schema
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->enum('role', ['subscriber', 'admin', 'basic', 'couple', 'family'])->default('subscriber');
$table->timestamp('email_verified_at')->nullable();
$table->string('avatar')->nullable();
$table->integer('no_of_logins')->default(0);
$table->date('sub_paid_at')->nullable();
$table->string('session_id')->nullable();
$table->string('password')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
I want to be able to update user role from the response, so I tried this
$user->role = $request->plan_object['name'];
But it returned error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'role' cannot be null (SQL: update users set role = ?, sub_paid_at = 1970-01-01 00:00:00, users.updated_at = 2019-12-14 08:40:46 where id = 3)
Change your variable name from paid_at to paidAt
$user->sub_paid_at = $request->paidAt;
But better you change format
$user->sub_paid_at = date("Y-m-d H:i:s",strtotime($request->paidAt));
This fix my question
$user = User::find(Auth::id());
$user->sub_paid_at = date("Y-m-d H:i:s",strtotime($paymentDetails['data']['paidAt']));
$user->role = $paymentDetails['data']['plan_object']['name'];
$user->save();
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.