Laravel - Update a table using Maatwebsite Excel Import based on condition - laravel

Using Laravel-5.8 and Maatwebsite-3.1, I have a table called employees (Employee).
class FirstEmployeeSheetImport implements ToModel, WithBatchInserts, WithHeadingRow, SkipsOnError, WithValidation, SkipsOnFailure
{
use Importable, SkipsErrors, SkipsFailures;
public function model(array $row)
{
$this->department = $row['department'];
$employee_data = [
'employee_code' => $row['employee_code'],
'company_id' => Auth::user()->company_id,
'email' => $row['official_email'],
'department_id' => $this->getDepartment(),
];
$employee = Employee::create($employee_data);
}
public function getDepartment(){
if(!empty($this->department) || !$this->department){
return HrDepartment::where('dept_name',$this->department)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
}
I want to use the excel upload to update these two (2) fields: email and department_id for each of the employees where:
company_id = Auth::user()->company_id AND employee_code = $row['employee_code'].
Also, it should only perform the update for those that meet the condition. I should only perform update and don't crete.
How do I achieve this?
Thanks

You can use ToCollection to get your data into $rows then update your data accordingly.
class FirstEmployeeSheetImport implements ToCollection
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
Employee::where('company_id', auth()->user()->company_id)
->where('employee_code', $row['employee_code'])
->update([
'email' => $row['email'],
...
]);
}
}
}

Related

Field doesnt have a default value while importing excel laravel

i want to import excel file to my database from the web. I have no idea what make it doesnt get the value from the excel, because i already try dd it and it shows the collection from the excel like what i want to do with it.
but its show error
SQLSTATE[HY000]: General error: 1364 Field 'kode_matkul' doesn't have a default value (SQL: insert into kelas () values ())
route :
Route::post('/admin/import_kelas_excel', 'DashboardController#importKelasExcel');
controller:
public function importKelasExcel(Request $request)
{
Excel::import(new KelasImport, $request->file('file'));
return redirect('admin/list_kelas')->with('status', 'Excel Berhasil Diimport !');
}
KelasImport :
namespace App\Imports;
use App\Kelas;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class KelasImport implements ToCollection, WithHeadingRow
{
public function collection(Collection $rows)
{
foreach ($rows as $row) {
Kelas::updateOrCreate([
'id' => $row['nomor'],
], [
'id' => $row['nomor'],
'kode_matkul' => $row['kode'],
'nama_matkul' => $row['matakuliah'],
'grup' => $row['grup'],
'sifat' => $row['sifat'],
'sks' => $row['sks'],
'jumlah_mhs' => $row['jumlah_mahasiswa'],
'tahun_ajaran' => $row['tahun_ajaran'],
'semester' => $row['semester'],
'jumlah_dosen' => $row['jumlah_dosen'],
]);
}
}
model :
protected $table="kelas";
protected $fillable = ["kode_matkul, nama_matkul, grup, sifat, sks, jumlah_mhs, prodi, tahun_ajaran, semester"];
public $timestamps = false;
excel :

laravel-medailibrary getFirstMediaUrl("images") not work for joined tables

I have a problem getting media from a joined table in laravel-medailibrary, I used getFirstMediaUrl("images") to get photos from one table and it works, but if I join two or three tables it not work, how can I solve it?
I want to get photos from those posts that shared by a user.
this post table:
this is share_tb table:
this is users table:
this is the media table:
I find my answer after trying some ways:
public function getPosts(Request $request)
{
$result = [];
$postID = DB::table("share_tb")->where("user_id", Auth::user()->id)->get();
foreach ($postID as $id) {
if (count(Post::where("id", $id->related_id)->get()) > 0) {
$posts = Post::where("id", $id->related_id)->get();
foreach ($posts as $post) {
// $result = $post->getMedia('images');
array_push($result, [
"comment_count" => getTotalComment($post->id),
"course_id" => $post->course_id,
"id" => $post->id,
'post_image' => count($post->getMedia('images')) > 0 ? $post->getMedia('images')[0]->getFullUrl('big') : "",
'logo'=>GetCourseLogo::collection(Course::where('course_id',$post->course_id)->get()),
"post_author" => $post->post_author,
"post_date" => $post->post_date,
"post_excerpt" => $post->post_excerpt,
"post_modified" => $post->post_modified,
"post_parent" => $post->post_parent,
"post_title" => $post->post_title,
"post_type" => $post->post_type,
]);
}
}
}
return Response()->json($result);
}
and by this resource collection, I get the logo:
class GetCourseLogo extends JsonResource
{
public function toArray($request)
{
return $this->getFirstMediaUrl('logo');
}
}

Laravel 7: How to use in data seeder array

How to make distinct inserts using a custom array using database seeder?
Using the following code:
$categories = ['Hardware', 'Software', 'Planning', 'Tools'];
foreach ($categories as $category) {
App\Category::insert([
'name' => $category,
'slug' => Str::slug($category),
]);
}
It doesn't work without a factory for a category that is the problem matter if I use insert or create.
It gives this error
Unable to locate factory for [App\Category].
at vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:273
269| */
270| protected function getRawAttributes(array $attributes = [])
271| {
272| if (! isset($this->definitions[$this->class])) {
> 273| throw new InvalidArgumentException("Unable to locate factory for [{$this->class}].");
274| }
275|
276| $definition = call_user_func(
277| $this->definitions[$this->class],
Thanks
Create an array of data in the run method of you seeder file
public function run()
{
$categories = [
['name' => 'Music'],
['name' => 'Gaming'],
['name' => 'Entertainment'],
['name' => 'Non-Profit & Activism'],
['name' => 'Other'],
];
foreach ($categories as $category) {
Category::create($category);
}
}
You are pushing all data into the Model, so you need to set fillable or guarded in the Model.
class Category extends Model
{
protected $guarded = [];
}
try using insert witch take an array as parameter:
public function run()
{
$inputs[] = ['name'=> 'Hardware'];
$inputs[] = ['name'=> 'Software'];
$inputs[] = ['name'=> 'Planning'];
$inputs[] = ['name'=> 'Tools'];
App\Category::insert($inputs);
}
or you can do it in another way:
public function run()
{
$inputsNames = ['Hardware', 'Software', 'Planning', 'Tools'];
foreach($inputsNames as $categoryName)
{
$inputs[]=['name'=>$categoryName];
}
App\Category::insert($inputs);
}

Base table or view not found: 1146 Table 'pht.location_id' doesn't exist

I have no table in my database in this name (location_id) but it gives me the error.
"message": "SQLSTATE[42S02]: Base table or view not found: 1146 Table
'pht.location_id' doesn't exist (SQL: select locations.*,
location_id.location_trails_id as pivot_location_trails_id,
location_id.location_id as pivot_location_id from locations
inner join location_id on locations.id =
location_id.location_id where location_id.location_trails_id
in (11, 13, 15, 16, 121, 123, 124, 181))",
I cannot find how to resolve it. Please Help me To resolve this issue. Thanks In advance.
Here is the code of my controller.
public function get($id)
{
$locations = LocationTrails::whereTrailId($id)->with('locations')->orderBy('ordered','ASC')->get();
dd($locations);
// $locations = Trail::findOrFail($id)->locations()->paginate($this->perPage);
// dd($locations);
$tdata = [];
foreach($locations->items() as $location) {
$hints = $location->hints;
$hintsData = [];
foreach($hints as $hint) {
$hintsData[] = [
'title' => $hint->title,
'hint_text' => $hint->hint_text,
'hint_solution_text' => $hint->hint_solution_text,
'hint_image_path' => $hint->hint_image_path,
'hint_video_path' => $hint->hint_video_path,
'complexity_order' => $hint->complexity_order
];
}
$tdata[] = [
'id' => $location->id,
'title' => $location->title,
'radius' => $location->radius,
'latitude' => $location->latitude,
'longitude' => $location->longitude,
'rewards_points' => $location->rewards_points,
'location_info_link' => $location->location_info_link,
'hints' => $hintsData
];
}
$data = [];
$data['data'] = $tdata;
$data['meta']['paginator'] = $this->getPaginatorInfo($locations);
return $data;
}
Here is my model of location
class Location extends Model
{
protected $table = 'locations';
protected $fillable = [
'title', 'radius', 'latitude', 'longitude', 'rewards_points', 'location_info_link', 'location_order'
];
/********************* RELATIONS *********************/
public function trails()
{
return $this->belongsToMany(Trail::class);
}
public function hints()
{
return $this->hasMany(LocationHint::class);
}
public function location_trails()
{
return $this->belongsTo(LocationTrails::class,'location_id');
}
Here is my locationtrail model:
class LocationTrails extends Model
{
protected $table = 'location_trail';
protected $fillable = [
'location_id', 'trail_id', 'ordered', 'created_at', 'updated_at',
];
/********************* RELATIONS *********************/
public function trails()
{
return $this->belongsToMany(Trail::class,'trail_id');
}
public function locations()
{
return $this->belongsToMany(Location::class,'location_id');
}
problem is in your LocationTrails model. You define your method like $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id'); so, laravel think location_id is a table name and the error thrown.
If it is one to many relationship.
public function locations()
{
return $this->hasMany(Location::class,'location_id');
}
If it is many to many relationship then you can see this.
https://laravel.com/docs/5.8/eloquent-relationships#many-to-many
same for your trails() method.
public function trails()
{
return $this->hasMany(Trail::class,'trail_id');
}

Is there any efficient method on how to get id of object to my create method

I am creating a web module, and want to get ID of table licensing level two parse into my create method. Hence each ID of level will have a task and the ID need to be stored within my licensing table as a foreign key which reflects ID in Level Two table. How could I solve this, anyone can give me a good suggestion or way on doing this
public function add_show($id)
{
$level = PreLicensingLevelTwo::where('id', $id)->first();
$level->prelicensingtask = PreLicensingTask::where('pre_licensing_level_two_id', $level->id)->with('staff', 'statusdesc', 'prelicensingtaskstaff')->get();
return view('staff.regulatory.statutory.approval.display',compact('level'));
}
public function create()
{
$staff = Staff::pluck('staff_name');
$status = PreLicensingStatus::pluck('status_description', 'id');
return view('staff.regulatory.statutory.approval.create', compact('staff','status'));
}
public function show($id)
{
$one = PreLicensingLevelOne::where('pre_licensing_main_id', $id)->get();
foreach ($one as $key => $license)
{
$license->two = PreLicensingLevelTwo::where('pre_licensing_level_one_id', $license->id)->get();
}
$rendered = view('staff.regulatory.statutory.approval.show')->with('one', $one)->render();
return response()->json(array('status' => 1, 'tableData' => $rendered));
}
With help from my working collegue this is how i able to solve the question i asked
public function store(Request $request)
{
$this->validate($request, [
'task_title' => 'required',
'task_description' => 'required',
'task_due_date' => 'required',
]);
$leveltwo = PreLicensingLevelTwo::find($request->input('pre_licensing_level_two_id'));
$prelicensingtask = new PreLicensingTask;
$prelicensingtask->task_title =$request->input('task_title');
$prelicensingtask->task_description =$request->input('task_description');
$prelicensingtask->task_due_date =$request->input('task_due_date');
$prelicensingtask->created_by_staff_id = Auth::user()->ref_user->staff_id;
$prelicensingtask->status = $request->input('status');
$prelicensingtask->pre_licensing_level_two_id = $leveltwo->id;
$prelicensingtask->pre_licensing_level_one_id = $leveltwo->pre_licensing_level_one_id;
$prelicensingtask->pre_licensing_main_id = $leveltwo->pre_licensing_main_id;
$prelicensingtask->centre_id = Auth::user()->ref_user->centre_id;
$prelicensingtask->save();
return redirect()->back();
}

Resources