How to seed foreign key in laravel - laravel

i am using spatie/laravel-permission package for roles and permissions
but getting problem in seed permanent role and permission here is database list link
https://github.com/spatie/laravel-permission/blob/master/database/migrations/create_permission_tables.php.stub
and i make these dataseeder for seeding
$this->call(UsersTableSeeder::class);
$this->call(PermissionsTableSeeder::class);
$this->call(RolesTableSeeder::class);
$this->call(RolehaspermissionTableSeeder::class);
$this->call(ModelhasrolesTableSeeder::class);
permissiontableseeder
DB::table('roles')->insert([
'name' => 'Administrator',
'guard_name' => 'web',
]);
RoleTableSeeder
DB::table('roles')->insert([
'name' => 'Admin',
'guard_name' => 'web',
]);
RolehaspermissionTableSeeder
DB::table('role_has_permissions')->insert([
'permission_id' => '1',
'role_id' => '1',
]);
ModelhasrolesTableSeeder
DB::table('model_has_roles')->insert([
'role_id' => '1',
'model_id' => '1',
'model_type' => 'App\User',
]);
here is screenshot of error
http://prntscr.com/h83ttx
Help me for seed this thanks

We can do like this...
$coursesIDs = DB::table('courses')->pluck('id');
$studentsIDs= DB::table('students')->pluck('id');
foreach (range(1,50) as $index) {
DB::table('course_student')->insert([
'course_id' => $faker->randomElement($coursesIDs)
'student_id' => $faker->randomElement($studentsIDs)
]);
}

check table name
DB::table('roles')->insert([
'name' => 'Administrator',
'guard_name' => 'web',
]);
on permissionstableseeder
this should be like this
DB::table('permissions')->insert([
'name' => 'Administrator',
'guard_name' => 'web',
]);
hope this helps you

Related

spatie permission There is no permission named `create` for guard `web`. laravel

i am using spatie permissions but it returns an error
There is no permission named `create` for guard `web`.
i don't know why please help
my code what am i doing is i create a new user then i create permissions then i make the user instructor have the permissions i create, all of that is in the seeder
here is my code seeder
public function run()
{
$user = User::create([
'name' => 'admin',
'email' => 'instructor#gmail.com',
'email_verified_at' => now(),
'password' => 'password', // password
'remember_token' => Str::random(10),
'type' => User::TYPE_INSTRUCTOR,
]);
$permissions =
[
[
'name' => 'methods_create',
'display_name' => 'create',
'key' => 'methods',
],
[
'name' => 'methods_update',
'display_name' => 'update',
'key' => 'methods',
],
[
'name' => 'methods_delete',
'display_name' => 'delete',
'key' => 'methods',
],
];
$role = Role::create(['name'=>'Instructor']);
foreach($permissions as $permission){
Permission::create($permission);
}
$role->givePermissionTo($permissions);
$user->assignRole($role);
}

Laravel Phpunit testing a request that take give output based on the request

I'm still new to laravel and I have a simple app and aSo I have a route that will store data based on the request in my controller.
public funtion store(Request $request, $id){
if ($request->has('work_experiences')) {
WorkExperience::create([
'user_id' => $user->id,
'position' => $request->work_experiences['position'],
'company' => $request->work_experiences['company'],
'start_date' => $request->work_experiences['start_date'],
'end_date' => $request->work_experiences['end_date'],
]);
}
if ($request->has('education')) {
Education::create([
'user_id' => $user->id,
'degree' => $request->education['degree'],
'university' => $request->education['university'],
'start_date' => $request->education['start_date'],
'end_date' => $request->education['end_date'],
]);
}
if ($request->has('job_interests')) {
JobInterest::create([
'user_id' => $user->id,
'job_position' => $request->job_interests['position'],
]);
}}
}
and in my test
public function test_authenticated_user_can_edit_education_profile()
{
$this->withoutExceptionHandling();
$user = User::factory()->create();
$this->actingAs($user);
$response = $this->post('/candidate' . '/' . $user->id, [
'user_id' => $user->id,
'position' => 'position',
'company' => 'company',
'start_date' => Carbon::now(),
'end_date' => Carbon::now(),
]);
$this->assertCount(1, WorkExperience::all());
}
when I run the test, the assertCount seems to fail because the response didn't work/insert the data to DB. where do I do wrong?
Well, the test is right.
It should fail because there is no work_experiences key in your request data.
The test request should look like:
$response = $this->post('/candidate' . '/' . $user->id, [
'work_experiences' => [
'user_id' => $user->id,
'position' => 'position',
'company' => 'company',
'start_date' => Carbon::now(),
'end_date' => Carbon::now(),
]
]);
So your data should go under a work_experiences key such that $request->has('work_experiences') returns true and executes the WorkExperience::create() statement.
Currently your endpoint only allows for a single "work experience" to be created. Seeing that you've named it work_experiences I assume you'd want to pass in an array/collection of "work experiences" - but that won't work with the current implementation; you'll have to loop over them instead - something like this:
if ($request->has('work_experiences')) {
foreach ($request->input('work_experiences') as $experience) {
WorkExperience::create([
'user_id' => $request->user()->id,
'position' => $experience['position'],
'company' => $experience['company'],
'start_date' => $experience['start_date'],
'end_date' => $experience['end_date'],
]);
}
}
And then your test should look something like this:
$response = $this->post('/candidate' . '/' . $user->id, [
'work_experiences' => [
[
'user_id' => $user->id,
'position' => 'position',
'company' => 'company',
'start_date' => Carbon::now(),
'end_date' => Carbon::now(),
],
// more "work experiences"
]
]);

Laravel: Setting a Default Value for Blank/Null Input

This is the code in the migration:
$table->string('role')->default('Standard');
When I leave the input box blank, it gives me an error:
"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'role' cannot be null
How do we set the default value to "Standard" if the input box is left blank?
Code for Controller
public function store(Request $request)
{
//return ['message' => 'I have your data'];
$request->validate([
'firstname' => 'required|string|max:191',
'lastname' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|string|min:6',
]);
return User::create([
'firstname' => $request['firstname'],
'lastname' => $request['lastname'],
'email' => $request['email'],
'phone' => $request['phone'],
'role' => $request['role'],
'usernotes' => $request['usernotes'],
'password' => Hash::make($request['password']), //make sure to import Hash: use Illuminate\Support\Facades\Hash;
'created_by' => $request['created_by'],
'updated_by' => $request['updated_by'],
]);
}
In your code $request['role'] should be null which is causing the problem since the role field is not Nullable.
What you can do is, add the dwfault value if the role is null, just made following changes in your code and it should work.
public function store(Request $request)
{
//return ['message' => 'I have your data'];
$request->validate([
'firstname' => 'required|string|max:191',
'lastname' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|string|min:6',
]);
return User::create([
'firstname' => $request['firstname'],
'lastname' => $request['lastname'],
'email' => $request['email'],
'phone' => $request['phone'],
'role' => $request['role'] ?? 'Standard',
'usernotes' => $request['usernotes'],
'password' => Hash::make($request['password']), //make sure to import Hash: use Illuminate\Support\Facades\Hash;
'created_by' => $request['created_by'],
'updated_by' => $request['updated_by'],
]);
}
That should fix the issue.
Explanation: I am using Null coalescing (??) operator of PHP which will replace the null value with 'Standard'. It works only is PHP 7+, if you have a lower version of PHP then you can consider using the Ternary operator(?:).
Reference: https://www.php.net/manual/en/migration70.new-features.php
use nullable();
$table->string('role')->default('Standard')->nullable();

mapWithKeys in laravel ,i dont understand how do it work?

I saw the example of laravel, but i dont understand how do it work.
for this example:
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john#example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane#example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
return [$item['email'] => $item['name']];
});
$keyed->all();
someone can explain detail of it?
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john#example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane#example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
//this line takes one array of collection object in item array and make a key of its email and store name on that email key
return [$item['email'] => $item['name']];
});
$keyed->all();

Laravel's db:seed is not inserting any record in database

I am using Laravel 5.6 and database seeder is not working. I am trying to insert 100 new data in my database but nothing is being inserted. No error is being shown and I don't know why php artisan db:seed is not working
Here's my DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$students = factory(App\Student::class, 100)->make();
}
}
Here's my StudentFactory.php
use Faker\Generator as Faker;
$factory->define(App\Student::class, function (Faker $faker) {
return [
'id' => $faker->unique()->numberBetween(1,1000),
'rfid_number' => $faker->unique()->numberBetween(1,1000),
'first_name' => $faker->firstName,
'middle_name' => $faker->lastName,
'last_name' => $faker->lastName,
'name_extension' => $faker->suffix,
'email' => $faker->safeEmail,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'photo' => '',
'house_number' => $faker->buildingNumber,
'barangay' => $faker->streetName,
'city' => $faker->city,
'province' => $faker->state,
'zip_code' => $faker->postCode,
'birth_date' => $faker->date('Y-m-d'),
'birth_place' => $faker->streetAddress,
'gender' => 'Male',
'religion' => 'Roman Catholic',
'landline_number' => $faker->tollFreePhoneNumber,
'mobile_number' => $faker->tollFreePhoneNumber,
'father_name' => $faker->name,
'father_occupation' => $faker->jobTitle,
'mother_name' => $faker->name,
'mother_occupation' => $faker->jobTitle,
'guardian_name' => $faker->name,
'guardian_occupation' => $faker->jobTitle,
'guardian_address' => $faker->streetAddress,
'year' => $faker->numberBetween(1,6),
'section' => $faker->cityPrefix,
'created_at' => now(),
'updated_at' => now()
];
});
and it shows no error.
Use create() method:
$students = factory(App\Student::class, 100)->create();

Resources