Import CSV Using Laravel Excel (Maat) - laravel-5

Hi I have an excel file with the details of passengers under the trip ID. I want to import that excel file in my table. please see the picture below:
the first row with the blue color is my column names on my table. my problem is how can I save the value of D2:G2 in next_of_kin table with this kind of format.
[
{"name":James Lara,"mobile":12345678},
{"name":Jasmine Lara,"mobile":12345678}
]
this is my code on my controller.
// Get excel file
$path = $request->file;
// Save the content to passenger
Excel::load($path, function ($reader) use ($request) {
$trip = Trip::where('id', $request->trip_customer_id)->first();
foreach ($reader->toArray() as $row) {
$trip->passengers()->create($row);
}
});

on my foreach inside the controller this looks like.
foreach ($reader->toArray() as $row) {
$given_name = array(
['name' =>$row['nok_one'],'mobile' => $row['nok_one_mobile']],
['name' =>$row['nok_two'],'mobile' => $row['nok_two_mobile']]
);
$trip->passengers()->create([
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'next_of_kin' => $given_name
]);
}

Related

How to upload file in relationship hasOn<->belongsTo Laravel Backpack

Can be possible to store a file uploaded to a related table?
Scenario: I have a usres table in database and another one pictures. Users Model have the following function
public function picture()
{
return $this->hasOne(Picture::class);
}
And the Picture Model have the following function.
public function user_picture()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?
try something like this
public function store(Request $request)
{
Picture::create([
'user_id' => // get the user id from $request or auth()->user(),
'img_path' => $request->file('image')->store('images', 'public'),
]);
return // your view or something else
}
Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :
public function store(Request $request)
{
$request->validate(...);
$user = User::create(...);
//It will ensure that the image belongs to the user.
$user->picture()->create([
'image_path' => $request->file('image')->store('images');
])
}
I resolved the issue with the following steps.
As per Laravel Backpack I added the input field in the Blade:
#include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
After this I added the function in the User Controller as follow:
$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
if($request->file()) {
$fileName1 = time().'_'.$request->img1->getClientOriginalName();
$filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}
With these lines of code I was able to store the related Picture with the User.
Thank you all for the guidelines.

updateOrcreate() record new data when i update existing data

I want to use method updateOrcreate(), when data is an empty new record to the database, but when data is existing is updated data,
like image bellow data is empty I want to record new data to database
like image bellow data is existing I want to update existing data and record to database
this is my code
public function simpanDataUn(Request $request)
{
$mapel_ujian_id = $request->mapel_ujian_id;
for($i=0; $i < count($mapel_ujian_id); $i++)
{
$arr = NilaiUjianAKhir::updateOrCreate([
'sekolah_id' => \Auth::user()->sekolah_id,
'siswa_id' => $request->id,
'mapel_ujian_id' => $request->mapel_ujian_id[$i],
'nilai_standar_daerah' => $request->nilai_standar_daerah[$i],
'predikat_standar_daerah' => $request->predikat_standar_daerah[$i],
'nilai_sekolah' => $request->nillai_sekolah[$i],
'predikat_nilai_sekolah' => $request->predikat_nillai_sekolah[$i],
'nilai_akhir' => $request->nilai_akhir[$i],
'predikat_nilai_akhir' => $request->predikat_nilai_akhir[$i],
],
[
'nilai_standar_daerah' => $request->nilai_standar_daerah[$i],
'predikat_standar_daerah' => $request->predikat_standar_daerah[$i],
'nilai_sekolah' => $request->nillai_sekolah[$i],
'predikat_nilai_sekolah' => $request->predikat_nillai_sekolah[$i],
'nilai_akhir' => $request->nilai_akhir[$i],
'predikat_nilai_akhir' => $request->predikat_nilai_akhir[$i],
]);
}
return redirect()->back()->with('success', 'Data UN berhasil di input');
}
I'm using updateOrCreate()method, but when i UPDATED existing data, the data
and even create new data, not updated existing data, like image below:
What part is wrong from my code? how to updated existing data using updateOrCreate() method?
please help me, thanks
Maybe you can change your code like this :
public function simpanDataUn(Request $request)
{
$mapel_ujian_id = $request->mapel_ujian_id;
for($i=0; $i < count($mapel_ujian_id); $i++)
{
$arr = NilaiUjianAKhir::updateOrCreate([
'sekolah_id' => \Auth::user()->sekolah_id,
'siswa_id' => $request->id,
'mapel_ujian_id' => $request->mapel_ujian_id[$i],
],
[
'nilai_standar_daerah' => $request->nilai_standar_daerah[$i],
'predikat_standar_daerah' => $request->predikat_standar_daerah[$i],
'nilai_sekolah' => $request->nillai_sekolah[$i],
'predikat_nilai_sekolah' => $request->predikat_nillai_sekolah[$i],
'nilai_akhir' => $request->nilai_akhir[$i],
'predikat_nilai_akhir' => $request->predikat_nilai_akhir[$i],
]);
}
return redirect()->back()->with('success', 'Data UN berhasil di input');
}
Like #lagbox say the first array passed to updateOrCreate are the where conditions to find a record ... if it can't find a record by those conditions it will create a new one. You won't create the new one when there's same sekolah_id, siswa_id or mapel_ujian_id right? Then the other field can be updated

Inserting and updating records from 3 tables in laravel

I am storing records for my product transfer app using 3 tables in single action. Transferhistories, Warehouse1StockSummaries and Warehouse2StockSummaries.
storing records to trasnferinghistories is ok, and also the increment method I declare to Warehouse2StockSummaries is also working fine except for Warehouse1StockSummaries.
here's my store function,
public function store(Request $request)
{
$input = $request->all();
$items = [];
for($i=0; $i<= count($input['product_id']); $i++) {
// if(empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
if(!isset($input['qty_in'][$i]) || !is_numeric($input['qty_in'][$i])) continue;
$acceptItem = [
'product_id' => $input['product_id'][$i],
'transfer_qty' => $input['qty_out'][$i],
'user_id' => $input['user_id'][$i]
];
array_push($items, Transferhistories::create($acceptItem));
// dd($input);
//update warehouse 1 summary
$warehouse1summary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
if (!$warehouse1summary->wasRecentlyCreated) {
$warehouse1summary->increment('qty_out', $input['qty_out'][$i]);
}
//update warehouse 2 summary
$stock2Summary = Warehouse2StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_out'][$i],'qty_out' => null]);
if (!$stock2Summary->wasRecentlyCreated) {
$stock2Summary->increment('qty_in', $input['qty_in'][$i]);
}
}
return redirect()->route('transferHistory.index');
}
updating warehouse 1 summary is not doing what it should be.
any suggestion master? thank you so much in advance!
According to laravel, firstOrCreate does not save the value, so after you do:
$warehouse1summary = Warehouse1StockSummaries::updateOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
Edit
The method firstOrNew will return the first or a instance of the Model.
So what you wanna do is this:
$warehouse1summary = Warehouse1StockSummaries::firstOrNew(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
if(isset($warehouse1summary->created_at)){
$warehouse1summary->qty_out = $warehouse1summary->qty_out + $input['qty_out'][$i];
}
$warehouse1summary->save();

Using pluck() helper function in laravel

I'm building a small application on laravel 5.5 where I'm getting a list of multiple users with there information, from the forms as below format:
{
"name":"Test",
"description":"Test the description",
"users":[
{
"value":"XYZabc123",
"name":"Nitish Kumar",
"email":"nitishkumar#noeticitservices.com"
},
{
"value":"MFnjMdNz2DIzMJJS",
"name":"Rajesh Kumar Sinha",
"email":"rajesh#noeticitservices.com"
}
]
}
I just want to get the value key form the users array via laravel collection something like this:
$userIds = $request->users->pluck('value');
so that I can put them into query:
$user = User::all()->whereIn('unique_id', $userIds);
May be I'm doing most of the things wrong but my main motive is to use laravel collection or helper functions and make a cleaner code for this:
$teamData['name'] = $request->name;
$teamData['description'] = $request->description;
$teamData['unique_id'] = str_random();
$users = $request->users;
$team = Team::create($teamData);
if($team)
{
$userIds = [];
foreach ($users as $user)
{
$getUser = User::where('unique_id', $user['value'])->get()->first();
$userIds [] = $getUser->id;
}
$team->users()->attach($userIds);
return response()->json(['message' => 'Created Successfully'], 200);
}
return response()->json(['message' => 'Something went wrong'], 500);
I'm still learning collections, any suggestions is appreciated. Thanks
Data that come from $request (form) isn't a collection. It's an array. If you need it to be collection, you should convert it to collection first.
PS. If you have multiple DB actions in single method, It's good to have DB transaction.
\DB::transaction(function () use ($request) {
// convert it to collection
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
});
// HTTP Created is 201 not 200
return response()->json(['message' => 'Created Successfully'], 201);
or you'll need something like this:
return \DB::transaction(function () use ($request) {
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
return response()->json([
'message' => 'Created Successfully',
'data' => $team,
], 201);
});
I just want to get the value key form the users array via laravel collection
Just use map then:
$userIds = $request->users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});
Edit:
if $request->users is not a collection, make it one before calling map:
$users = collect($request->users);
$userIds = $users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});

How to upload multiple images from two different file uploads fields in single form in laravel?

How can I pass multiple images files from two separate file upload option in my form and then store into database? Here are my schema and controller codes.
Schema::create('images', function (Blueprint $table) {
$table->increments('image_id');
$table->increments('book_id')->unsigned();
$table->string('coverPageImage');
$table->string('previewPageImage');
$table->timestamps();
});
Form Fields: BookID, File Upload for coverPageImage, File Upload for
previewPageImage. Both coverPageImage and previewPageImage pass multiple images.
I was able to upload images into folder and save to database for single file upload.
$product_images = $request->file('coverPageImage');
foreach($product_images as $product_image){
$coverImage_name = $product_image->getClientOriginalName();
$upload = $product_image->move('images', $coverImage_name);
Image::create([
'book_id' => $book_id,
'cover_images' => $coverImage_name
]);
}
$preview_pages = $request->file('previewPageImage')
foreach($preview_pages as $preview_image){
$previewImage_name = $preview_image->getClientOriginalName();
$upload = $preview_image->move('images', $previewImage_name);
Image::create([
'book_id' => $book_id,
'preview_images' => $previewImage_name
]);
}
I want to use following way:
Image::create([
'book_id' => $book_id,
'cover_images' => $coverImage_name,
'preview_images' => $previewImage_name
]);
But I am stuck while using foreach loop for two different fileuploads. Any suggestions or hints.
If you are sure there will always be a 1:1 relationship between the $coverImage_name and the $previewImage_name, then you can just push them into an array, loop the array, and create your images from within.
$images = [];
$product_images = $request->file('coverPageImage');
foreach ($product_images as $idx => $product_image){
$coverImage_name = $product_image->getClientOriginalName();
$upload = $product_image->move('images', $coverImage_name);
$images[$idx]['cover_image'] = $coverImage_name;
}
$preview_pages = $request->file('previewPageImage')
foreach($preview_pages as $idx => $preview_image){
$previewImage_name = $preview_image->getClientOriginalName();
$upload = $preview_image->move('images', $previewImage_name);
$images[$idx]['preview_image'] = $previewImage_name;
}
foreach($images as $idx => $arr) {
Image::create([
'book_id' => $book_id,
'cover_images' => isset($arr['cover_image']) ? $arr['cover_image'] : null,
'preview_image' => isset($arr['preview_image']) ? $arr['preview_image'] : null
]);
}

Resources