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

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();

Related

I cant get lastInsertId on laravel 7 project

$sql = DB::table('laravel_products')
->insert(array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
));
$lastInsertedID = $sql->lastInsertId();
When I try to insert its responses:
"Call to a member function lastInsertId() on bool"
I used insertGetId but its cant save multiple rows of pictures on mysql.
If you want to get the last inserted ID like that you can call that method on the PDO instance directly:
$id = DB::getPdo()->lastInsertId();
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
from : https://laravel.com/docs/5.8/queries#inserts
$data = new LaravelProducts(); //LaravelProducts is your Model Name
$data->name= $name; //here 'name' is your column name
$data->price= $price; //here 'price' is your column name
$data->qty= $qty; //here 'qty' is your column name
$data->description= $description; //here 'description' is your column name
..........
..........
$data->image= $image; //here 'image' is your column name
$data->save();
$lastInsertedId = $data->id;
You don't have to write a new query to collect last inserted id from database.
$laravel_product = DB::table('laravel_products')
->insertGetId( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
foreach ($filenamesToSave as $filename) {
DB::insert('INSERT INTO laravel_products_images ( product_id, filename ) VALUES ( ?, ? )',[$laravel_product->id, $filename]);
return view('createproduct');
} // Foreach Closing
// Echo your inserted ID Like Below
echo $laravel_product->id;
It should be 100% working for you.

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 - How to Dynamically implement my API

I am consuming an external API using Guzzle and saving it into database:
use App\Employee;
public function handle()
{
$client = new GuzzleHttp\Client();
$res = $client->request('GET','https://api.employees.net/allemployees');
$clientdatas = json_decode($res->getBody()->getContents(), true);
foreach($clientdatas as $clientdata)
{
$employee = HrEmployee::updateOrCreate([
'employee_code' => $clientdata['staff_id'],
],
[
'first_name' => $clientdata['first_name'],
'last_name' => $clientdata['last_name'],
'other_name' => $clientdata['middle_name'],
'dept_code' => $clientdata['department_id']
]);
}
}
Currently what I have is that if
'employee_code' => $clientdata['staff_id'],
exists, it should update
[
'first_name' => $clientdata['first_name'],
'last_name' => $clientdata['last_name'],
'other_name' => $clientdata['middle_name'],
'dept_code' => $clientdata['department_id']
]);
it should save new records.
However, I want to change it that if
'employee_code' => $clientdata['staff_id'],
exists, it should update
[
'first_name' => $clientdata['first_name'],
'last_name' => $clientdata['last_name'],
'other_name' => $clientdata['middle_name'],
]);
except
[
'dept_code' => $clientdata['department_id']
]);
If not, it should save everything
How do I achieve this?
Thanks
Create payloads based on $clientdata['staff_id']
$payloads = [
'first_name' => $clientdata['first_name'],
'last_name' => $clientdata['last_name'],
'other_name' => $clientdata['middle_name']
];
if(!isset($clientdata['staff_id']) { // only add dept_code if staff_id is not set
$payloads['dept_code'] = $clientdata['department_id'];
}
$employee = HrEmployee::updateOrCreate([
'employee_code' => $clientdata['staff_id'],
], $payloads);

Validation fails even if it has values Maatwebsite Laravel Validation

I'm currently using Maatwebsite collection when processing the import CSV file and validating it as well since I'm having hard time using the ToModel way. Here's how I validate the csv fields:
class ImportRooms implements ToCollection, WithStartRow
{
public function collection(Collection $rows)
{
foreach($rows as $row){
\Validator::make($row->toArray(), [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5],
'name' => ['required', 'max:50'],
'room_code' => ['required', 'max:50'],
'user_name' => ['required', 'max:255'],
'email' => ['required', 'email', 'max:255','nullable'],
'password' => ['min:8','max:255','nullable'],
'remarks' => ['max:500'],
])->validate();
}
}
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
}
This is a sample data I have.
Illuminate\Support\Collection {#565 ▼
#items: array:6 [▼
0 => "Room name"
1 => "Room101"
2 => "user"
3 => "fmacejkovic#example.org"
4 => "password"
5 => "remarks"
]
}
My problem now is that even though the values are all correct and valid, it still fails in the validation. I'm trying to assign to a specific variable so that when it fails, it'll return the row name instead of row number. Even though I use the row number, it still fails.
You have used incorrect syntax for Validator::make(), use this :
class ImportRooms implements ToCollection, WithStartRow
{
public function collection(Collection $rows)
{
foreach($rows as $row){
$row = $row->toArray();
$data = [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5],
];
\Validator::make($data, [
'name' => ['required', 'max:50'],
'room_code' => ['required', 'max:50'],
'user_name' => ['required', 'max:255'],
'email' => ['required', 'email', 'max:255','nullable'],
'password' => ['min:8','max:255','nullable'],
'remarks' => ['max:500'],
])->validate();
}
}
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
}
Refer https://laravel.com/docs/5.8/validation#automatic-redirection
//Convert row data into array and store it in a variable.
$row = $row->toArray();
//Set data to be validated.
$data = [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5]
];
//Set conditions for validation.
$conditions = [
'name' => 'required|max:50',
'room_code' => 'required|max:50',
'user_name' => 'required|max:255',
'email' => 'required|email|max:255|nullable',
'password' => 'min:8|max:255|nullable',
'remarks' => 'max:500'
];
//Validate the excel data.
\Validator::make($data, $conditions)->validate();

How to seed foreign key in 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

Resources