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();
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.
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}}">
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.
i am very new in Laravel and this is my first project in Laravel.As usual, first of all i am developing a full user authentication system.I can registered an single user,can send an user verification email and after clicking that link i can activate a new user account, can login and can logout.But after that whenever i am trying to registered another new user and after clicking the verification link , i am facing an exception which is,
Illuminate \ Database \ QueryException
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'users_code_unique' (SQL: update `users` set `code` = , `active` = 1, `updated_at` = 2014-07- 25 04:26:06 where `id` = 41)
now this is my route.php,
<?php
Route::get('/',array(
'as' =>'home',
'uses' =>'HomeController#index'
));
Route::get('/signin',array(
'as' =>'signin',
'uses' =>'AccountController#signinGet'
));
Route::get('/signup',array(
'as' => 'signup',
'uses' => 'AccountController#signupGet'
));
/*
/*
/Authenticated Group
*/
Route::group(array('before' => 'auth'),function(){
/*
/Sign Out(GET)
*/
Route::get('/signout',array
(
'as' => 'signout',
'uses' => 'AccountController#signoutGet'
));
});
/*
/UnAuthenticated Group
*/
Route::group(array('before' => 'guest'),function(){
/* CSRF Protect*/
Route::group(array('before' => 'csrf'),function(){
/*
/ Create Account(POST)
*/
Route::post('/signup',array(
'as'=> 'signup',
'uses'=>'AccountController#signupPost'
));
/*
/ Sign In(POST)
*/
Route::post('/signin',array(
'as' => 'signin-post',
'uses' => 'AccountController#signinPost'
));
});
/*
/ Sign In (GET)
*/
Route::get('/signin',array(
'as' => 'signin',
'uses' => 'AccountController#signinGet'
));
/*
/Create Account(GET)
*/
Route::get('/signup',array(
'as' => 'signup',
'uses'=> 'AccountController#signupGet'
));
Route::get('signup/account/activate/{code}',array(
'as' =>'activate-account',
'uses' =>'AccountController#activatePost'
));
});
?>
and this is my AccountController
<?php
class AccountController extends \BaseController {
public function signinGet()
{
return View::make('account.signin');
}
public function signinPost(){
$validator = Validator::make(Input::all(),array(
'email' => 'required|email',
'password' => 'required'
));
if($validator->fails()){
//redirect to the signin page
return Redirect::route('signin')
->withErrors($validator)
->withInput();
}else{
//Attempt user singin
$auth = Auth::attempt(array
(
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1
));
if($auth){
//Redirect To intented URL
return Redirect::intended('/');
}
else
{
return Redirect::route('signin')
->with('global','The username or password you provided is wrong or account not activated!');
}
}
return Redirect::route('signin')
->with('global','There is a problem Signing You in.');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function signupGet()
{
return View::make('account.signup');
}
public function signupPost()
{
$validator = Validator::make(Input::all(), array(
'email' => 'required|max:255|email|unique:users',
'username' => 'required|min:3|unique:users',
'password' => 'required|min:6',
'password_again' => 'required|same:password'
)
);
if($validator->fails())
{
return Redirect::route('signup')
->withErrors($validator)
->withInput();
}else
{
$email = Input::get('email');
$username = Input::get('username');
$password = Input::get('password');
//Activation Code
$code = str_random(60);
$user = User::create(array(
'email' => $email,
'username' => $username,
'password' => Hash::make($password),
'code' => $code,
'active' => 0
)
);
if($user){
//User Activation Code Creation
Mail::send('emails.auth.activate', array('link' => URL::route('activate-account',$code), 'username' => $username),function($message) use ($user)
{
$message->to($user->email,$user->username)->subject('Activate Your Account');
});
return Redirect::route('signup')
->with('global','Your Account has been created! We have sent you an email to activate your account.Please Check the both the Inbox and Spam Folder.');
}
}
//return 'This is a Post Result';
}
public function activatePost($code){
$user = User::where('code','=',$code)->where('active','=',0);
if($user->count()){
$user = $user->first();
$user->active = 1;
$user->code = '';
if($user->save()){
return Redirect::route('home')
->with('global','Activated!.You can sign in now!');
}
}
else{
return Redirect::route('signup')
->with('global','Sorry!We could not activate your acount,please try again later.');
}
}
public function signoutGet(){
Auth::logout();
return Redirect::route('home');
}
}
?>
and this is my create user migration file
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username',255)->unique();
$table->string('email',255)->unique();
$table->string('password',60);
$table->string('password_temp',60);
$table->string('code',60)->unique();
$table->integer('active');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
?>
and this is my user.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
protected $fillable = array('email','username','password','password_temp','code','active');
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
?>
now whats the problem?
Make sure your code field is nullable, then instead of setting it's value to empty string, make it null:
$code = null;
Then you will be able to save it as NULL (MySQL) while it remains unique.
Also change this one:
$user = User::where('code','=',$code)->where('active','=',0);
if($user->count()){
$user = $user->first();
To:
$user = User::where('code','=',$code)->where('active','=',0)->first();
if(count($user)){
You don't need to call db twice, just check if returned result is not null (count will do), meaning it returned a User object.
your problem can use validator to check. simply use as this:
use Validator;
use Request;
//...
//unique will pre check the key code weather if unique in tbl_name
public function yourfunc(Request $request) {
// set the rules to check
$rules = ['code'=>'required|unique:tbl_name'];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
// handler errors
$erros = $validator->errors();
}
//... everything is ok here
}
you can explore more at laravel validation
I found it. You've set code column as unique, though you're setting it to empty string after user click an activation link. And there already is a row in table with code=''; so it throws an error. The problem is here (activatePost):
$user->code = '';
So either don't empty it, set it to something else or set db colums as not unique.
I would leave the code without emptying it and additionally I would check if user was activated - a simple if in activatePost. Maybe it's a good idea to verify user not only according to code, but also with a hashed id in link.
There a few things you need to do to improve your code. But duplicate entry usually happens when you set a column to unique and tries to re inset the same data into another row. The most time it get confusing is when you check your table and and find the column empty. Whoop! When a column is set to unique and empty, it means no other column can contain empty data.
In simple terms the form of the column can not be duplicated, either null or with data.
Integrity constraint violation Duplicate entry problems are due to database schema inconsistence being detected by laravel.
Integrity constraint violation Duplicate entry problems are likely to occur when the database schema was preserved by laravel migration, and then the db scheme is updated somehow outside of laravel migration's control (eg. developers manually (without via performing a laravel migration) alter the db schema in a db client OR the db scheme is updated by importing a piece of SQL dump that is inconsistent with the db scheme -- as a result of that, the importing unexpectedly updates the laravel-migration-preserved db schema.
To avoid the second kind of harm, be careful when importing SQL dump data into db: ensure the SQL dump data is consistent with the current db schema before your SQL dump is imported.
Overall, when doing laravel development, the db schema should always be preserved by laravel migration to avoid db schema inconsistence.