Create Profile Model Before User Import With Laravel Excel - laravel

I'm Importing My Users through Excel using the Laravel Excel Package
I want to create a profile Model before importing users. How do I do this?
The user table has a 1: 1 relationship with the profile table. This means that each user has one profile
User Table :
id username password is-admin created_at updated_at department_id
1 4480115617 $2y$10$HUBeOzDlTvaJKmI8d5GXJ.qzbqsDcDooi4WG0BrOAHOE9Ce3HMgC6 1 2021-04-16 10:07:34 2021-06-24 04:51:18 10
52 4480124152 $2y$10$.hOMGBCdcrBNx6UbQ4vAOeInnma6mjnztRxL2k8kpV/vK2dEWrj8O 0 2021-07-08 08:01:07 2021-07-08 08:01:07 1
53 12345678910 $2y$10$5d.FMSRyf/KT8bOtQYaSA.BZMLVEKFgjiXL/pjfHCMXmZ7tbZgnPW 1 2021-07-08 08:02:07 2021-07-08 08:02:07 2
54 4420827661 $2y$10$TE8biYPPHhv7ZdUfmY11sO9.7QXOaqKAyWkOEbgsBxJi2uq2iLFs2 1 2021-07-13 06:50:38 2021-07-13 06:50:38 3
Profile Table :
id user_id avatar_src phone address email created_at updated_at field_id name family father national_code
6 1 users/avatars/default.jpg 0xxxxxxxxxxx یزد aa#asdag.com (NULL) 2021-06-24 04:51:18 (NULL) محمد غریب
21 52 users/avatars/52.jpg 09134576502 adasdasdasdasdas mohamm#taho.com 2021-07-08 08:01:08 2021-07-13 06:54:05 (NULL) محمد کریمی
22 53 users/avatars/default.jpg 09134575052 daasdasd asda#yaho.com 2021-07-08 08:02:07 2021-07-08 08:02:07 (NULL) مسعود رامینی
23 54 users/avatars/default.jpg 09134576502 قلثقلقثقثقثث reza#yaho.com 2021-07-13 06:50:38 2021-07-13 06:50:38 (NULL) مهدی رضایی

Assuming you are using a custom import class, if not you many want to use a custom import class by creating a new class called UsersImport in app/Importsdefined in the docs.
UsersImport.php
namespace App\Imports;
use App\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class UsersImport implements ToCollection
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
// We are creating an instance to use it to create the profile
$user = User::create([
'username' => $row[0], //or name of the col with $row['username']
'password' => $row[1],
'is-admin' => $row[2],
'department_id' => $row[3]
]);
// create the profile using $user and one-to-one relationship
// assuming your relationship is profile() defined in User Model
$user->profile()->create([
'avatar_src' => $row['avatar_src'],
'phone' => $row['phone'],
//... your other columns
]);
}
}
}
Next call your method in Database Seeder with Excel::import(new UsersImport, storage_path('Pathtolfile.xlsx'));

Related

Laravel - Table with two columns, each has ID from different tables

I need to create a single objective that has a multi-select drop down wherein different departments can share that same objective. I wanted to create a relationship table with an output like this.
Department Table
id | name
1 Science Department
2 Math Department
3 Biology Department
Objective Table
id | name
1 Be the best
Relationship Table
objective_id | department_id
1 1
1 2
1 3
This is what I think of inside the controller.
public function store(Request $request) {
$objective = Objective::updateOrCreate(
[ 'id' => $request->id ?? null ],
[ 'name' => $request->name ]
);
// From multiple select drop down
foreach($request->departments as $department) {
RelationshipTable::updateOrCreate(
[ // what should be the case? ],
[
'objective_id' => $objective->id,
'department_id' => $department['id'],
]
);
}
}
I'm not sure on how I would define this in the Model and how I could call their relationship inside the resource. I even think that my controller is wrong or are there better ways to achieve this?
First You are running query under loop is a very bad process.. may this process will help u? change it as your need!
public function store(Request $request) {
$objective = Objective::updateOrCreate(
[
'id' => $request->id ?? null,
'name' => $request->name
]
);
// From multiple select drop down
$insert_array = [];
foreach($request->departments as $department) {
array_push($insert_array,[
'objective_id' => $objective->id,
'department_id' => $department['id'],
]);
}
RelationshipTable::updateOrCreate($insert_array);
}
//Relationship Should Be Like in this example
Relationship Model
public function object() {
return $this->hasOne('Model Class of Object' , 'objective_id ' , 'id')
}
public function depertment() {
return $this->hasMany('Model Class of depertment' , 'department_id' , 'id')
}

How to get hasMany relation in laravel?

Pls bear with me . I am working on api with laravel :
The Idea is that I have table called ( cards ) this table contain column called ( service_id ) .
this column has relation with table ( services ).
This is cards database structure in image :
image of database
All thing is good with add one service_id , but now I need to make table cards hasMany services
So How can I do it , and the database structure what will be?
this is my old code to add new card :
public function store(Request $request)
{
$validator = \Validator::make($request->all(), [
'user_id' => 'required|unique:cards|exists:users,id',
'service_id' => 'required',
'numPhone' => 'required',
'location' => 'required',
],[],[
'user_id' => '( User id )',
'service_id' => 'service id',
'numPhone' => 'Phone Number',
]);
if ($validator->fails()){
return $this->apiRespone(null,$validator->errors()->all(),'Some input required');
}
$card = Card::create($request->all());
return $this->apiRespone(new cardResource($card),'Add card Successfully',201);
}
I think you need to create pivot table "cards_services" that has column id, card_id, service_id column and used relationship Sync() method of laravel to store/update.
In cards modal
public function services(){
return $this->belongsToMany('App\Models\Service','cards_services', 'card_id', 'service_id');
}
For save it.
$cards->services()->sync([1,2]); //1 and 2 is service ID and $cards is card modal object
here you have service_id in your cards table
so i think it will be easier to implement service hasMany cards and cards belongsTo service
add this in your service model
public function cards(){return $this->hasMany('App\Cards');}
add this in your cards model
public function service(){return $this->belongsTo('App\Service');}
Note: please rewrite path and Model name according to your requirement

How to pluck data for a form

I'd like to show names on my select dropdown
I have 3 tables: 'users','users_pro' and 'practice'
users : id ,name ,dob ,.. etc
users_pro : id ,user_id,..etc
practice : id , user_pro_id ,...etc
I want to input data to table 'practice' and I want to make a select dropdown using pluck on users_pro with users like this :
public function input_practice()
{
$data= Users_pro::with('users')->get()->pluck('id','user_id');
dd($data);
// return view('admin.input.input_riwayat_kgb',
// [
// 'data'=>$data,
// ]);
}
If I dd($data), I get :
Collection {#327 ▼
#items: array:4 [▼
6 => 3 // 6 is user_id ,and 3 is 'id' on users_pro , i need to show 'name' like 3 => 'jhon'
13 => 4
12 => 5
14 => 6
]
}
But I want to show the name of the user on my select dropdown. Can someone help me?
You are trying to pull a collection and then get the name and id from the relationship models within. Thus, you will get an error that the property does not exist on the collection because it is many User_pro objects and then tries to get user data from each one of the relations would require a loop.
Assuming you have a users relationship set up on the User_pro model, you can get your dropdown list like this:
$data= User::whereHas('user_pro')->pluck('name','id');
This gives you a collection of users (who happen to be pros) and then plucks the name and id of your users for you to use in your dropdown.
This is solved with this line :
$data = Users_pro::with('users')->get()->pluck('users.nama', 'id');

Get list of submitted fees along with date from fees table using student_id as foreign key

I have a students table and fees table.
students
--------------
|id | name |
--------------
fees
---------------------------------------------------------
| id| student_id | paid_fees | created_at | updated_at |
---------------------------------------------------------
Here, student_id from fees is foreign key that references to id on students.
I have two models for these tables, and I have defined a hasMany relationship between them.
Because ,A student can submit the total fees in parts, So he can have more than one record in fees table
Student.php
lass Student extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'roll_no', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function fees(){
return $this->hasMany('App\StudentFees');
}
}
Fee.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Fees extends Model
{
public function student(){
return $this->belongsTo('App\Student');
}
}
I tried to get all the occurenece of the records related to the srudent_id.
$student->fees->where('student_id', $student - >id)
It gives me an arrays of the records as a object. Please suggest if there is a better way.
I am trying to get paid_fee record which is related to a student_id with created_at or updated_at record too.
Maybe like this: [ [2500, '2019-05-19], [3500, '2019-06-28'] ]
So I am trying to get a list of all submitted fees along with date related to student_id.
Once you get your StudentFees object you can access the Student with just $studentFee->student.
But if you need absolutely that kind of output, you can write something like
$studentFees = StudentFees::all();
if ($studentFees) {
$output = $studentFees->map(function($fee) {
return [ $fee->paid_fees, $fee->student->created_at ];
});
// do whatever you want with $output;
}
In my thinking, you created your file Fee.php and your class model is StudentFees. it seems to be not match.i think you should rename that file is StudentFees.php.

datamapper orm advanced relationship

I use datamapper orm with codeigniter
my table is:
person
id, name, related_person1_id, related_person2_id
person can have 1 related_person1, 1 related_person2
how can i set the relationship in my model file ?
it is described in the docu:
class Person extends DataMapper {
$has_many = array(
'related_person' => array(
'class' => 'person',
'other_field' => 'person',
'reciprocal' => TRUE
),
'person' => array(
'other_field' => 'related_person',
'reciprocal' => TRUE
)
);
}
how can I set in for more than 1 related person ? and how shold i set up my table ? i wanna stay with 1 "person" table.
THX
Best bet is to create a separate table for relationships.
So you have a person table:
id:int
name:text
then a relationship table
id:int
person_id:int
related_to_person_id:int
relationship
This way you can have as many relationships per person as you want.
Persons:
id | name
1 | Jimmy Doublechin
2 | Opie Hardabs
3 | Anthony Predator
Relationships:
id | person_id | related_to_person_id | relationship
1 | 1 | 2 | lover
2 | 1 | 3 | best buddy evar
3 | 3 | 2 | Mother
Then
class Person extends Datamapper {
public $has_many = array('relationships');
...
class Relationships extends Datamapper {
public $has_one = array('person');
....

Resources