I'm trying to create an entry for a Contact:
Contact::create([
'firstname' => $faker->firstName,
'lastname' => $faker->lastName,
'email' => $faker->email,
'location_id' => 6,
'department_id' => 3
]);
In the model Contact.php:
protected $fillable = [
'firstname',
'lastname',
'location_id',
'department_id',
'email'
];
The migration code:
Schema::create('contacts', function(Blueprint $table)
{
$table->increments('id');
$table->string('firstname');
$table->string('lastname');
$table->integer('location_id')->nullable();
$table->integer('department_id')->nullable();
$table->string('email')->unique();
$table->timestamps();
});
If I just try to create it with firstname, lastname, and email, it works fine. But for some reason it doesn't work with the location_id and department_id fields filled in. The entry doesn't appear in the db, but there is no error message. What am I doing wrong?
Let's try this
// app/models/Location.php
class Location extends Eloquent { }
// app/models/Department.php
class Department extends Eloquent { }
and the migration to update
Schema::create('contacts', function(Blueprint $table)
{
$table->increments('id');
$table->string('firstname');
$table->string('lastname');
$table->integer('location_id')->unsigned();
$table->integer('department_id')->unsigned();
$table->string('email')->unique();
$table->timestamps();
});
Related
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('/');
}
I'm newbie in laravel and I'm working on a project including JWT.
I've changed the user table that was generated by Laravel:
instead of 'name' column , I replaced to 'first_name' and 'last_name' columns.
like that:
Schema::create('users', function (Blueprint $table)
{
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->string('username');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
}
I followed the instructions to add the JWT and created AuthController as said.
my Register function looks like that:
public function register(Request $request)
{
$user = User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'username' => $request->username,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$token = auth()->login($user);
return $this->respondWithToken($token);
}
after checking on Postman, the user was created and added to the table, but without token.
so the request returns empty token. like that:
{
"access_token": null,
"token_type": "bearer",
"expires_in": 3600
};
Why is that?
maybe it's because I've changed the origin columns at the users table?
And what should I do to fix it?
thank you.
I guess you should do the migrations again after you have made some changes to the original columns. But you might have done that already.
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?
I have been trying to create a record of a table B using the id of a created record in table A. But for some reason, the field is always null even though i have dumped the value of the model id and it's correct. but when i assign it to a field in table B it doesn't insert it. I don't get any errors, and both records are created(in Table A and B) but the value of the field that is supposed to have the ID of model A is NULL.
I have added the field to the $fillable array in the model class:
protected $fillable = [
'name', 'email', 'password', 'phone', 'role', 'A_id',
];
Here is the code I tried. Please help me solve this issue.
if($data['role'] == 'admin'){
$tableA = TableA::create([
'name' => $data['name'],
'phone' =>$data['phone']
]);
return TableB::create([
'A_id' => $tableA->id,
'name' => $data['nameB'],
'email' => $data['email'],
'role' => $data['role'],
'phone' => $data['phoneB'],
'password' => bcrypt($data['password']),
]);
}
Here is the migration file for TableB
public function up()
{
Schema::create('tableB', function (Blueprint $table) {
$table->increments('id');
$table->integer('A_id')->unsigned()->nullable();
$table->string('phone', 10)->unique();
$table->string('name');
$table->string('role');
$table->integer('address_id')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
Add A_id to the $fillable array in the TableB model:
protected $fillable = ['A_id', ......];
After Being confused for quite some time. I have tried a different way to create the model and for some reason, it's just working fine.
if($data['role'] == 'admin'){
$tableA = TableA::create([
'name' => $data['name'],
'phone' =>$data['phone']
]);
$tableB = new TableB();
$tableB->A_id = $tableA->id;
$tableB->name = $data['nameB'];
$tableB->email = $data['email'];
$tableB->role = $data['role'];
$tableB->phone = $data['phoneB'];
$tableB->password = bcrypt($data['password']);
$tableB->save();
return $tableB;
}
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());
});