store data in tables - laravel

how can i store data to database in tables
i have two tables in my migration
I want to save the "firstName" to "usersAppointments" table but, it always trying to save the data to "appointments" table
"I'm Beginner"
MIGRATION
public function up()
{
Schema::create('appointments', function (Blueprint $table) {
$table->id();
$table->string('');
$table->string('');
$table->date('');
$table->timestamps();
});
Schema::create('usersAppointments', function (Blueprint $table) {
$table->id();
$table->string('firstName');
$table->timestamps();
});
}
CONTROLLER
public function store(Request $request){
$data = $request->validate([
'' => 'required',
'' => 'required',
'' => 'required'
]);
Appointment::create($data);
return redirect('/');
}
public function usersAppointment(Request $request){
$data = $request->validate([
'firstName' => 'required'
]);
Appointment::create($data);
return redirect('/');
MODEL
protected $fillable = [
'', '', '',
'firstName'
];

That's because of trying to insert the data into 'Appointment'.
you must write the code as below :
public function usersAppointment(Request $request){
$data = $request->validate([
'firstName' => 'required'
]);
UsersAppointment::create($data);
return redirect('/');
}

Related

having issue with referral system laravel

so i was trying to build a basic referral system where new registered can input there referral username and the referral count will increase and also the referral table will be populated with the referral id and newly user id
i am not getting or doing it right need help
public function register()
{
$user = User::create([
// 'name' => $this->name,
'username' => $this->username,
'email' => $this->email,
'password' => encrypt($this->password)
]);
if ($user = User::where('username', $this->referral)->first()) {
$user->increment('referrel_count');
$user = Referral::create([
'user_id' => auth()->id,
'referred_by_id' => $user->id,
]);
}
$user->notify(new WelcomeUser($user));
Auth::login($user);
return redirect(route('profile.show', auth()->user()->username));
}
table
public function up()
{
Schema::create('referrals', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->string('referred_by_id')->references('id')->on('users');
$table->timestamps();
});
}
model user
public function referral()
{
return $this->belongsToMany(Referral::class);
}
referral model
public function users()
{
return $this->belongsToMany(User::class);
}

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null?

I got this error when try to seed database.
Laravel 7.
BlogPost Model
class BlogPost extends Model
{
protected $fillable = [
'title',
'slug',
'user_id',
'category_id',
'excerpt',
'content_raw',
'content_html',
'is_published',
'published_at',
'updated_at',
'created_at',
];
public function category()
{
return $this->belongsTo(BlogCategory::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
User model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
User migration
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->rememberToken();
$table->timestamps();
});
BlogPost migration
Schema::create('blog_posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id');
$table->foreignId('user_id')->constrained();
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt')->nullable();
$table->text('content_raw');
$table->text('content_html');
$table->boolean('is_published')->default(false)->index();
$table->timestamp('published_at')->nullable();
$table->foreign('category_id')->references('id')->on('blog_categories');
$table->timestamps();
});
User seeder
class UserTableSeeder extends Seeder
{
public function run()
{
$users = [
[
'name' => 'Author',
'email' => 'seriiburduja#mail.ru',
'password' => bcrypt('some1234')
],
[
'name' => 'Admin',
'email' => 'seriiburduja#gmail.com',
'password' => bcrypt('some1234')
]
];
DB::table('users')->insert($users);
}
}
BlogPost Factory
$factory->define(BlogPost::class, function (Faker $faker) {
$title = $faker->sentence(rand(3, 8), true);
$text = $faker->realText(rand(1000, 4000));
$isPublished = rand(1, 5) > 1;
$createdAt = $faker->dateTimeBetween('-6 months', '-1 day');
return [
'category_id' => rand(1, 10),
'user_id' => 1,
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
});
DatabaseSeeder
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(UserTableSeeder::class);
$this->call(BlogCategorySeeder::class);
factory(BlogPost::class, 1)->create();
}
}
When i run php artisan migrate:fresh --seed i got this error.
Tables users and blog_categories seeds successfully, but error appear for blog_categories.
I don't understand why.
Field user_id exists in $fillable in BlogPost Model.
If i change migration for blog_posts and add a nullable for user_id, than seed work, but user_id is null. But i don't need that.
Thansk in advance.
In Blog Post Model
Change user relationship to
public function owner()
{
return $this->belongsTo(User::class);
}
In User Model
Add this relationship
public function blogposts()
{
return $this->hasMany(BlogPost::class);
}
In Database seeder don't use UserSeeder Directly create user in DatabaseSeeder
public function run()
{
$user = User::create([
'name' => "Your name",
'email' => "youremail#gmail.com",
'password' => Hash::make('YourPassword')
]);
$this->call(BlogCategorySeeder::class);
$user->blogposts()->saveMany(BlogPost::factory(1));
}
In BlogPost Factory remove user_id
return [
'category_id' => rand(1, 10),
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
fillable is not required when you are using Seeder to insert data.
If you want to insert each and every column in database then you can use guarded property which is opposite of fillable.

Save Many-To-Many Relationship in Laravel 6

i have two table Product and Order that Many-To-Many to each other. so, i created one other Table Middle of them order_table.
I try to save relationship many-to-many, but i got error unit_price doesnt have a default value.
in Product Model
protected $fillable = [
'name', 'price', 'description', 'status'
];
public function orders()
{
return $this->belongsToMany(\App\Order::class);
}
in Order Model
protected $fillable = [
'description', 'ref_no', 'customer_id', 'description', 'active'
];
public function products()
{
return $this->belongsTo(\App\Product::class);
}
And in Order_Product Schema
Schema::create('order_product', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('order_id');
$table->unsignedBigInteger('product_id');
$table->double('unit_price');
$table->integer('quantity')->default(1);
$table->timestamps();
$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
In ProductController
public function create(Request $request)
{
$request->validate([
'name' => 'required',
'price' => 'required',
'description' => 'nullable',
]);
$product = new Product();
$product->name = $request->input('name');
$product->price = $request->input('price');
$product->status = $request->input('status');
$product->description = $request->input('description');
$product->save();
$orders = new \App\Order();
$orders->unit_price = $request->unit_price;
$product->orders()->attach($orders);
return response()->json(['created' => true]);
}
I'll appreciate of all ur help.... Thanks....
Validate the Data to insure it exists.
$data = $this->validate($request, [
'unit_price' => 'required|numeric'
]);
$data['unit_price'];
Use the get method and specify a fallback
$product->orders()->attach($order, [
'unit_price' => $request->get('unit_price', 0)
]);
Fill the pivot using "only" for ease of use once you have it worked out:
$product->orders()->attach(
$order, $request->only(['unit_price'])
);
I got error unit_price doesn't have a default value.
This is a Database issue. Please set a default value for unit_price column.

Integrity constraint violation Laravel 5.8

I have a ‘recurring_payments’ table
Schema::create('recurring_payments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('user_id');
$table->string('card_id');
$table->string('day');
$table->integer('amount');
$table->timestamps();
});
I have a ‘card’ table
Schema::create('cards', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('token');
$table->string('last4');
$table->timestamps();
$table->softDeletes();
});
I have a ‘belongs to’ relationship between a ‘recurring_payment’ and a ‘card’
class RecurringPayment extends Model
{
protected $guarded = [];
public function card()
{
return $this->belongsTo(Card::class, 'token');
}
}
When I try to store the recurring payment
class Card extends Model
{
use SoftDeletes;
protected $fillable = [
'user_id',
'token',
'last4',
];
protected $hidden = [
'user_id',
'token',
'created_at',
'updated_at',
];
...
public function storeRecurringPayment($payment, $user)
{
$attributes = [
'user_id' => $user,
'card_id' => $payment->source['id'],
'day' => Carbon::now()->day()->addMonths(1)->format('d'),
'amount' => $payment->amount
];
// dd($attributes);
return $this->recurringPayment()->create($attributes);
}
public function recurringPayment()
{
return $this->hasOne(RecurringPayment::class);
}
...
}
it will not populate the ‘card_id’, it complains that the ‘card_id’ cannot be null, which is what I want, so far enough, but the ‘card_id’ is populated, this is the $attributes array died and dumped just before it's passed to the 'return $this->recurringPayment()->create($attributes);'
array:4 [▼
"user_id" => 3
"card_id" => "src_4zcdnrruvgxetpkgxocg6hhk5m"
"day" => "30"
"amount" => 10
]
I’m specifying in the ‘recurring_payment’ that I want to use ‘token’ as the foreign key not the default ‘card_id’ but I still get this error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'card_id' cannot be null (SQL: insert into 'recurring_payments' ('user_id', 'card_id', 'day', 'amount', 'updated_at', 'created_at') values (3, ?, 30, 10, 2019-07-11 13:53:08, 2019-07-11 13:53:08))
Can anyone see the mistake I've made?

Factory model relationships in Laravel

I have 2 tables named Users and Users_meta. Both are sharing One-To-One relationship. I would like to insert dummy data with the help of seeding. I am able to do that, the only thing that is driving me crazy is that, I am unable to establish relationship between users and users_meta table with user_id as foreign key. I tried few ways but that either creates duplicate entires with same user_id or keeps repeating the same user_id.
What exactly I would like is; when creating for example 100 records, after first user record insertion, it should take the same user's user_ID, add it to users_meta table's user_id field and repeat the insertion till 100 fake records.
Any help on this would be greatly appreciated
Code in : UserFactory.php
$factory->define(App\User::class, function (Faker $faker) {
static $password;
return [
'username' => $faker->userName,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'referral_code' => str_random(10),
'referred_by_code' => str_random(10),
'role' => $faker->randomElement(['administrator', 'user', 'volunteer']),
'remember_token' => str_random(10),
]; });
Code in : UsersMetaFactory.php
$factory->define(App\Usersmeta::class, function (Faker $faker) {
return [
'user_id' => $faker->randomElement(\App\User::pluck('id')->toArray()),
'first_name' => $faker->firstname,
'last_name' => $faker->lastname,
'gender' => $faker->randomElement(['male', 'female']),
'date_of_birth' => $faker->dateTimeThisCentury->format('Y-m-d'),
'address' => $faker->address,
'city' => $faker->city,
'state' => $faker->state,
'zip_code' => $faker->postcode,
'country' => $faker->country,
'cell_phone' => $faker->e164PhoneNumber,
'bitcoin_address' => str_random(16),
'monero_address' => str_random(16),
'security_question' => $faker->realText($maxNbChars = 20, $indexSize = 2),
'security_answer' => $faker->realText($maxNbChars = 40, $indexSize = 2),
'is_founder' => $faker->boolean($chanceOfGettingTrue = 50),
'status' => $faker->randomElement(['active', 'inactive']),
'terms' => $faker->boolean
]; });
The randomElement() method gives me random id which violates one to one relationship principal and my app breaks down. I would like it should fetch id from users table and pass the same id as user_id to users_meta table and continue generating fake records.
CreateUsersTable migration class
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->string('referral_code')->unique();
$table->string('referred_by_code');
$table->enum('role', ['administrator', 'user', 'volunteer'])->nullable();
$table->rememberToken();
$table->timestamps();
});
}
CreateUsersMetaTable migration class
public function up()
{
Schema::create('users_meta', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('first_name');
$table->string('last_name');
$table->enum('gender', ['male', 'female'])->nullable();
$table->string('date_of_birth')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('zip_code')->nullable();
$table->string('country');
$table->string('cell_phone');
$table->string('bitcoin_address')->nullable();
$table->string('monero_address')->nullable();
$table->string('security_question');
$table->string('security_answer');
$table->string('is_founder')->nullable();
$table->enum('status', ['active', 'inactive'])->nullable();
$table->string('terms');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users_meta');
Schema::enableForeignKeyConstraints();
}
You should remove this line:
'user_id' => $faker->randomElement(\App\User::pluck('id')->toArray()),
And use relationship when creating a new model. Here's a modified example from the docs:
factory(App\User::class, 50)->create()->each(function ($u) {
$u->usersmeta()->save(factory(App\Usersmeta::class)->make());
});

Resources