Save to user database from a Json response in Laravel - php

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();

Related

Larevel - Save last user request timestamp

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.

SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value

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();
}

how to fix :SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

how i can fix this error ?
this is my error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(coachers.article_comments, CONSTRAINT
article_comments_user_id_foreign FOREIGN KEY (user_id) REFERENCES
users (id)) (SQL: insert into article_comments (name, email,
description, article_id, user_id, updated_at, created_at)
values (aaaaa, aaa#gmail.com, hhhhhhsssshhshsh, 1, 0, 2019-10-17
08:12:17, 2019-10-17 08:12:17))
public function commentArticle($user_id, $article_id, Request $request)
{
if (!$user_id == 0) {
$register = $request->validate([
'description' => 'required|min:5',
]);
$commentarticle = new articleComment();
$commentarticle->description = $request->input('description');
$commentarticle->user_id = $user_id;
$commentarticle->article_id = $article_id;
$commentarticle->name = 'name';
$commentarticle->email = 'email';
$commentarticle->submit = 0;
$commentarticle->save();
return $request;
}
else if ($user_id == 0) {
$register = $request->validate([
'description' => 'required|min:5',
'name' => 'required|min:3',
'email' => 'required|min:5|max:150|email',
]);
$comment = new articleComment();
$comment->name = $request->input('name');
$comment->email = $request->input('email');
$comment->description = $request->input('description');
$comment->article_id = $article_id;
$comment->user_id = 0;
$comment->save();
return $comment;
}
}
and my api :
Route::post('comment-article/{user_id}/{article_id}', 'ArticleController#commentArticle');
and my table
public function up()
{
Schema::create('article_comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('user_id')->unique()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('article_id')->unique()->nullable();
$table->foreign('article_id')->references('id')->on('articles');
$table->string('name')->nullable();
$table->string('email')->nullable();
$table->string('submit')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
}
remove unique() method from user_id and article_id column and rerun migration again..
public function up()
{
Schema::create('article_comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('article_id')->nullable();
$table->foreign('article_id')->references('id')->on('articles');
$table->string('name')->nullable();
$table->string('email')->nullable();
$table->string('submit')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
}
if user_id is not there then user_id set a null not a (zero)0
$comment->user_id = NULL;
It looks like there is no user with id == 0 in your users table. And since there is a foreign key constraint the operation fails.

Integrity constraint violation: 1048 Column 'company_id' cannot be null laravel5.3

I am try to set the (Table company )(Company id -> primary key) to the foreign key in (Table branch)(company_id).
Controller:
public function savebranchinfo(Request $request){
$validator = Validator::make($request->all(),[
'name' => 'required|min:5',
'email' =>'required|unique:branch',
'address' =>'required',
'contact' =>'required|min:11',
'open_hours' =>'required',
]);
if($validator->passes()){
$branch = new Branch();
$branch->company_id = $request->company_id;
$branch->name = $request->name;
$branch->email = $request->email;
$branch->address = $request->address;
$branch->contact = $request->contact;
$branch->open_hours = $request->open_hours;
if($branch->save()){
$request->session()->flash('message','Successfully save!!');
return redirect('/add/branch');
}
}else{
return redirect('/add/branch')->withErrors($validator)->withInput();
}
}
}
Migration:
public function up()
{
Schema::create('branch', function (Blueprint $table) {
$table->increments('id');
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('company');
$table->String('name');
$table->String('email');
$table->String('address');
$table->String('contact');
$table->String('open_hours');
$table->timestamps();
});
}
View :
<input type="hidden" value="company_id{{$company->id}}">
Error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'company_id' cannot be null (SQL: insert into branch (company_id, name, email, address, contact, open_hours, updated_at, created_at) values (, Mahmood Son, mahmoodson#gmail.com, bilal gunj, 04237152734, 8am-8pm, 2017-02-25 12:06:35, 2017-02-25 12:06:35))
It seems to me you forgot the input name in the form:
<input type="hidden" name="company_id" value="{{$company->id}}">

Laravel 5 SQLSTATE[23000] users_email_unique

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.

Categories