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}}">
Related
I am new to Laravel framework.
I am facing an issue, with migration of User table.I added nullable to 'firstname' of my table, which works but displaying the same error for 'lastname'column. I have included nullable() to every column, which is not the right way to do it. How to solve this?? Can anyone please suggest.
User migration table, facing issue with the 'firstname' column.
create_user_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('firstname');
$table->string('lastname');
$table->string('email')->unique();
$table->date('dob');
$table->char('address',100);
$table->bigInteger('phonenumber');
});
}
UserController with store
UserController.php
public function store(Request $request)
{
$request->validate([
'firstname'=>'required',
'lastname'=>'required',
'email'=>'required',
]);
$user=new User([
$user->firstname=>$request->get('firstname'),
'lastname'=>$request->get('lastname'),
'email'=>$request->get('email'),
'dob'=>$request->get('dob'),
'address'=>$request->get('address'),
'phonenumber'=>$request->get('phonenumber')
]);
$user->save();
return redirect('/users')->with('success','user added');
}
The easiest way to achieve this is:
public function store(Request $request)
{
$request->validate([
'firstname'=>'required',
'lastname'=>'required',
'email'=>'required',
]);
$user=new User();
$user->firstname = $request->firstname;
$user->lastname = $request->lastname;
$user->email = $request->email;
$user->dob = $request->dob;
$user->address = $request->address;
$user->phonenumber = $request->phonenumber;
$user->save();
return redirect('/users')->with('success','user added');
}
Also in your model, you have to add this line for mass assignment
protected $fillable = ['firstname','lastname','email','dob','address','phonenumber'];
You may check out this link for mass assignment: https://laravel.com/docs/7.x/eloquent#mass-assignment
There is an errors in the code you posted,
Here is the fix:
public function store(Request $request)
{
$request->validate([
'firstname'=>'required',
'lastname'=>'required',
'email'=>'required',
]);
$user=new User([
'firstname' => $request->get('firstname'), // $user->firstname=>$request->get('firstname'),
'lastname'=> $request->get('lastname'),
'email' => $request->get('email'),
'dob' => $request->get('dob'),
'address' => $request->get('address'),
'phonenumber' => $request->get('phonenumber')
]);
$user->save();
return redirect('/users')->with('success','user added');
}
also here you are using mass assignment so you should add all used columns to your fillable array in your User model.
Here is a link on what is mass assignment
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.
hi i have 3 table 1st is products 2nd is category 3rd is designer
products and category is many to many relationship
product belongsto designer & designer hasMany products
designer belongsto category & category hasMany designers
here is my table
product
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('image');
$table->string('stock');
$table->string('title');
$table->string('slug')->unique();
$table->string('gender');
$table->text('description');
$table->integer('price');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('restrict')
->onUpdate('restrict');
$table->dateTime('published_at');
});
designers table
Schema::create('designers', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->timestamps();
});
category table
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
Schema::create('category_product', function (Blueprint $table) {
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')
->onDelete('restrict')
->onUpdate('restrict');
$table->integer('product_id')->unsigned()->index();
$table->foreign('product_id')->references('id')->on('products')
->onDelete('restrict')
->onUpdate('restrict');
$table->timestamps();
});
adding missing column in products table
Schema::table('products', function (Blueprint $table) {
$table->integer('designer_id')->unsigned();
$table->foreign('designer_id')->references('id')->on('designers')
->onDelete('restrict')
->onUpdate('restrict');
});
adding missing column in designer
Schema::table('designers', function (Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')
->onDelete('restrict')
->onUpdate('restrict');
});
here is my controller
public function productpost(Request $request){
$this->validate($request, [
'title' => 'required|max:255',
'description' => 'required',
'price' => 'required',
'image' => 'image|required',
]);
$designer_name = $request->designer;
$designer_slug = str_random(40);
$designer = designer::where('name', $designer_name)->firstOrCreate(
['name' => $designer_name], ['slug' => $designer_slug]
);
$designer->name = $designer_name;
$designer->slug = $designer_slug;
$designer->save();
$designer_id = $designer->id;
$product = new Product;
$product->title = $request->title;
$product->designer_id = $designer_id;
$product->description = $request->description;
$product->price = $request->price;
$product->stock = $request->stock;
$product->gender = $request->gender;
$product_slug = str_random(40);
$product->slug = $product_slug;
$product->user_id = Auth::user()->id;
$product->published_at = Carbon::now()->format('Y-m-d');
if($request->hasFile('image')) {
$file = Input::file('image');
//getting timestamp
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$file->move(public_path().'/images/product/', $name);
$product->image = $name;
$thumb = Image::make(public_path().'/images/product/' . $name)->resize(1200,1800)->save(public_path().'/images/product/thumb/' . $name, 90);
}
$product->save();
$productsearch = product::where('slug', $product_slug)->firstorfail();
$product_id = $productsearch->id;
$categoryname = $request->category;
foreach ($categoryname as $name) {
$category = category::firstOrNew(['name' => $name]);
$category->designer_id = $designer_id;
$category->save();
$category->products()->attach($product_id);
}
return Redirect::back()->with('status', 'Post Success');
missing is product need designerid
designer need category_id
category need product_id
how to solve this on controller thank you
You can't update the designer_id column in that way unless you've added designer_id to the fillable array in your model.
Alternatively, you can use the Eloquent methods by simply doing $product->designer()->associate($designer); instead of $product->designer_id = $designer->id.
If you haven't already, you'll also need to setup a relationship on the Product model.
public function designer() {
return $this->belongsTo(Designer::class, 'designer_id');
}
Trying to Update user Profile after Login and am having this ERROR:
QueryException in Connection.php line 662:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`wallet`.`profiles`, CONSTRAINT `profiles_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `profiles` (`gender`, `city`, `state`, `profession`, `aboutmyself`, `fb`, `twitter`, `gp`, `instagram`, `personal_site`, `aboutme`, `linkedin`, `pinterest`, `updated_at`, `created_at`) values (male, Upper Darby, Washington DC, Architects, Am a Benefactor of Grace and a Heir to the Throne a Royal Priesthood. I Love Jesus! s, url, url, url, url, url, url, hurl, url, 2016-11-05 09:35:51, 2016-11-05 09:35:51))
AND THIS
PDOException in Connection.php line 390:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`wallet`.`profiles`, CONSTRAINT `profiles_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
Meaning that part of the CODE is executing now but something on Integrity Violation is hindering the data from being saved.
CONTROLLER (UserController.php)
public function update(Request $request)
{
$rules = [
'name' => 'required',
'email' => 'required',
'phone' => 'required|numeric',
'country' => 'required',
'gender' => 'required',
'birthday' => 'required',
'fb' => 'url',
'twitter' => 'url',
'gp' => 'url',
'instagram' => 'url',
'personal_site' => 'url',
'aboutme' => 'url',
'linkedin' => 'url',
'pinterest' => 'url'
];
$data= $request->all();
$validator = Validator::make($data, $rules);
if($validator->fails()){
return Redirect::back()->withInput()->withErrors($validator);
}
$user = Auth::user();
$user->name = $data['name'];
$user->email = $data['email'];
$user->phone = $data['phone'];
$user->country = $data['country'];
$user->birthday = $data['birthday'];
$user->address = $data['address'];
if($user->save()) {
$profile_id = $user->id;
$profile = Profile::findOrFail($user->id);
if(count($profile) > 0) {
$profile = new Profile();
$profile->gender = $data['gender'];
$profile->city = $data['city'];
$profile->state = $data['state'];
$profile->profession = $data['profession'];
$profile->aboutmyself = $data['aboutmyself'];
$profile->fb = $data['fb'];
$profile->twitter = $data['twitter'];
$profile->gp = $data['gp'];
$profile->instagram = $data['instagram'];
$profile->personal_site = $data['personal_site'];
$profile->aboutme = $data['aboutme'];
$profile->linkedin = $data['linkedin'];
$profile->pinterest = $data['pinterest'];
//$profile = $user->profile()->save($profile);
$profile->save();
}
} else {
return redirect()->back()->withInput()->withInfo("Something went wrong. Please, try again");
}
return redirect()->route('profile')->withSuccess("Your Profile Succesfully Updated.");
}
USER Migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('login');
$table->string('email')->nullable();
$table->string('phone')->nullable();
$table->string('password', 60);
$table->string('birthday');
$table->string('country')->default('AF');
$table->string('address');
$table->integer('active')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
PROFILE Migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
// $table->string('birthday');
$table->string('aboutmyself');
$table->string('gender');
$table->string('age');
$table->string('propic')->default('uploads/demo.png');
$table->string('address');
$table->string('state');
$table->string('city');
$table->string('fb');
$table->string('twitter');
$table->string('gp');
$table->string('personal_site');
$table->string('instagram');
$table->string('aboutme');
$table->string('linkedin');
$table->string('pinterest');
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('profiles');
}
}
It's a lot of code to look through, however, I think your issue may lie with the $fillable array on your User model. It appears that you have added extra columns to you users table without allowing them to be mass assigned, so you need to make sure you add them to the $fillable array as so:
protected $fillable = ['name', 'login','email', 'password', 'country', 'birthday'...];
See: https://laravel.com/docs/5.3/eloquent#mass-assignment
You should also really be using a FormRequest for a validator that size to prevent it from clogging up your controller:
https://laravel.com/docs/5.3/validation#form-request-validation
And you should look at how to save relationships:
https://laravel.com/docs/5.3/eloquent-relationships#inserting-and-updating-related-models
You should note that eloquent automatically maps your input fields to database columns with the same name so you should really be able to break that controller method down to just a few lines of code.
You violate foreign key contraint. You don't add anything to $profile->user_id and it stays null and your database disallows that. Simply add $profile->user_id = $user->id; after $profile = new Profile(); and it should work.