Laravel Bulk Insert To Another Table From Selected Multiple Rows - laravel

I expected I can replicate multiple row from specific table to another table. But the problem, it cannot replicate password field data and spatie assignRole(). Whereas, all fields like email, name, username, etc are works properly.
public function approveMultiple(Request $request) {
$get_ids = $request->ids;
$ids = explode(',', $get_ids);
$users = \App\Applicant::whereIn('id', $ids);
$users->update(['status' => 'Approved']);
$find_selected = \App\Applicant::whereIn('id', $ids)->get();
$find_selected->makeHidden(['status', 'id']);
$find_selected->makeVisible(['password']);
$new_users = $find_selected->toArray();
$users = \App\User::insert($new_users);
//problem still lays here
//$users->assignRole('Applicant');
//$users->save();
return response()->json(['success' => "Selected User(s) successfully approved."]);
}
Trying to this approach but only insert one record
public function approveMultiple(Request $request) {
$get_ids = $request->ids;
$ids = explode(',', $get_ids);
//$users = \App\Applicant::whereIn('id', $ids);
//$users->update(['status' => 'Approved']);
//$find_selected = \App\Applicant::whereIn('id', $ids)->get();
$find_selected = \App\Applicant::whereIn('id', $ids)->firstOrFail();
$find_selected->makeHidden(['status', 'id']);
$find_selected->makeVisible(['password']);
$new_users = $find_selected->toArray();
//$users = \App\User::insert($new_users);
$users = \App\User::create([
'name' => $find_selected->name,
'username' => $find_selected->username,
'gender' => $find_selected->gender,
'email' => $find_selected->email,
'phone' => $find_selected->phone,
'password' => $find_selected->password,
'created_at' => $find_selected->created_at,
'updated_at' => $find_selected->updated_at,
]);
//problem lays here
$users->assignRole('Applicant');
$users->save();
return response()->json(['success' => "Selected User(s) successfully approved."]);
}

about password field , you need to make it visible with function like : makeVisible
for example:
$users->makeVisible('password')->toArray();
Edit 1:
about assignRole you must assign the role after you call the save() method
for example:
$users->password = $find_selected->password;
$users->save();
$users->assignRole('Applicant');
Edit 2:
public function approveMultiple(Request $request) {
$get_ids = $request->ids;
$ids = explode(',', $get_ids);
//$users = \App\Applicant::whereIn('id', $ids);
//$users->update(['status' => 'Approved']);
$find_selected = \App\Applicant::whereIn('id', $ids)->get();
//$find_selected = \App\Applicant::whereIn('id', $ids)->firstOrFail();
$find_selected->makeHidden(['status', 'id']);
$find_selected->makeVisible(['password']);
$new_users = $find_selected->toArray();
//$users = \App\User::insert($new_users);
foreach($find_selected as $new_users){
$user = \App\User::create($new_users);
$user->assignRole('Applicant');
}
return response()->json(['success' => "Selected User(s) successfully approved."]);
}

i think the problem lays in this line:
$users = \App\User::insert($new_users);
insert method returns a boolean that indicate the insertion operation has succeeded or not ...
so you $users variable will hold a boolean value ...
and
$users->assignRole('Applicant');
$users->password = $find_selected->password;
wont work
you could use :
$find_selected->makeVisible(['password']);
foreach($find_selected as $user)
{
$newUser= new User();
$newUser->password = $user->password;
$newUser->save();
$newUser->assignRole('Applicant');
}

Related

Get Raw SQL of Insert Statement

I am looking for a way to get the correct SQL queries for an INSERT statement. I'm having to export this data for use in another (non-laravel) system. The post at How to get the raw SQL for a Laravel delete/update/insert statement? got me part of the way there but my queries are still parameterized:
Post::all()->each(function($post)
{
$builder = DB::table('posts');
$insertStatement = $builder->getGrammar()->compileInsert($builder->select(['created_at', 'title']), [
'created_at' => $post->created_at,
'title' => $post->title
]);
Storage::disk('sql')->append('posts-latest.sql', $insertStatement);
dump($insertStatement);
}
this results in...
insert into `posts` (`created_at`, `title`) values (?, ?)
So I've managed to set the fields to be updated but how to swap out the parameters for real values?
You can do this:
Post::all()->each(function($post){
$builder = DB::table('posts');
$grammar = $builder->getGrammar();
$values = [
'created_at' => $post->created_at,
'title' => $post->title
];
$table = $grammar->wrapTable($builder->from);
if (!is_array(reset($values))) {
$values = [$values];
}
$columns = $grammar->columnize(array_keys(reset($values)));
$parameters = collect($values)->map(function ($record) use ($grammar) {
$record = array_map(function($rec){
$rec = str_replace("'", "''", $rec);
return "'$rec'";
},array_values($record));
return '('.implode(', ', $record).')';
})->implode(', ');
$insertStatement = "insert into $table ($columns) values $parameters";
// $insertStatement should contains everything you need for this post
});
I ended up discovering DB::pretend which will generate the query without running it. Then it's a case of substitution. It seems that there is no way to get the raw SQL without substitution due to the use of parameters.
Post::all()->each(function($post)
{
$builder = DB::table('posts');
$query = DB::pretend(function() use ($builder, $post)
{
return $builder->insert([
'created_at' => $post->created_at,
'title' => $post->title,
'content' => $post->content,
'featured_image_link' => $post->featured_image_link,
'slug' => $post->slug
]);
});
$bindings = [];
collect($query[0]['bindings'])->each(function($binding) use (&$bindings)
{
$binding = str_replace("'", "\\'", $binding);
$bindings[] = "'$binding'";
});
$insertStatement = Str::replaceArray('?', $bindings, $query[0]['query']);
Storage::disk('sql')->append('posts-latest.sql', $insertStatement.';');
});

Validation can not updating value in database

I am uses validation for gst and adhar but when its error free i am updating value but value can not updating. I am giving updating code in else part. what is mistake done by me? need a solution. In if part i am checking validation and in else part if error is not coming, i am updating value from table but i can not work.
public function profile_update(Request $req,$id)
{
$mytime = Carbon::now();
$fullname = $req->input('fullname');
$email = $req->input('email');
$mobile = $req->input('mobile');
$gender = $req->input('gender');
$gstnumber = $req->input('gst_number');
$adharnumber = $req->input('aadhar_number');
$password = $req->input('password');
$cpassword = $req->input('c_password');
$updated_at = $mytime->toDateTimeString();
$created_at = $mytime->toDateTimeString();
$validator = Validator::make($req->all(), [
'email' => 'email|unique:users,email',
'aadhar_number' => 'unique:users,aadhar_number' ,
'gst_number' => 'regex:^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$^|unique:users,gst_number'
]);
if($validator->fails())
{
//dd("hello");
$messages = $validator->messages();
//return Redirect::to('/customer')->with('message', 'Register Failed');
return redirect('/profile')
->withErrors($validator)
->withInput();
}
else
{
if ($req->hasFile('update_image'))
{
$image = $req->file('update_image');
$filename = $image->getClientOriginalName();
$destinationPath = public_path('/images/users_profile/');
$image->move($destinationPath, $filename);
DB::update(
'update users set name = ?,email = ?,mobile = ?,image = ?,gender = ?,gst_number=?,aadhar_number=?,password = ?,cpassword = ? where id = ?',
[$fullname, $email, $mobile, $filename, $gender, $gstnumber, $adharnumber, $password, $cpassword, $id]
);
}
else
{
DB::update(
'update users set name = ?,email = ?,mobile = ?,gender = ?,gst_number=?,aadhar_number=?,password = ?,cpassword = ? where id = ?',
[$fullname, $email, $mobile, $gender, $gstnumber, $adharnumber, $password, $cpassword, $id]
);
}
return redirect('/profile');
}
}
you dont need the if else statement
$req->validate([
'email' => 'email|unique:users,email',
'aadhar_number' => 'unique:users,aadhar_number' ,
'gst_number' => 'regex:^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$^|unique:users,gst_number'
// continue your update code here
]);
Simply do this and it will do the needfull for you
if your conditions are not met by the values it will return to the previous view and if the conditions are met, it will continue to run the codes.
for updating the data
$data = user::find(id);
$data->name = $name;
$data->email = $email;
.
.
.
.
//update all the fields
$data->save();

Laravel isDirty method mass assignment

My code is saving data of only one field(efirst) if it's changed by the isDirty() method, and it's working correctly. How can I achieve the same result if I have ten fields without writing each field name?
Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
$teacher->efirst = $request->efirst;
if ($teacher->isDirty()) {
$new_data = $teacher->efirst;
$old_data = $teacher->getOriginal('efirst');
if ($teacher->save()) {
$teacher->update($request->except('qual_id', 'id', 'profile_pic'));
DB::table('teacher_logs')->insert(
[
'user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $old_data,
'new_value' => $new_data,
]);
}
}
}
If you don't want to write $teacher->field = $request->value; a bunch of times, you may use a loop:
foreach($request->except("_token") AS $field => $value){
$teacher->{$field} = $value;
}
if($teacher->isDirty()){
$new_data = [];
$old_data = [];
foreach($request->except("_token") AS $field => $value){
$new_data[$field] = $value;
$old_data[$field] = $teacher->getOriginal($field);
}
}
Note: You'll need to convert $new_data and $old_data to arrays so you can reference each field and value properly, and do some additional logic on the insert of your teacher_logs table to handle, but that should give you an idea.

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

codeigniter get last insert id from model to use as redirect parameter

I need to get the insert ID to be used in my controller, the problem is my model function has several data arrays, and I need the insert ID of the 1st array. therefor if I try to get the insert ID on my controller obviously its grabbing the 2nd insert ID and not the 1st.
I'm not sure this makes sense but here is an example:
Model
public function add() {
$data = array(
'name' => $_POST['companyName']
,'type' => $_POST['companyType']
,'active' => '1');
$this->db->insert('company', $data);
$cid = $this->db->insert_id();
$data2 = array(
'cid' => $cid
,'name' => $_POST['locationName']
,'address' => $_POST['locationAddress']);
$this->db->insert('locations', $data2);
}
This is working fine...However after this runs, on my controller the redirect is getting the data2 last insert which makes my redirect wrong.
Controller
public function add() {
if (isset($_POST["add"]))
{
$this->Company_model->add();
$id = $this->db->insert_id();
redirect('company/view/'.$cid);
}
$data['states'] = $this->Company_model->
}
Any help would be greatful!
You were very close. Instead of repeating $id = $this->db->insert_id(); in your controller, you can return the $cid from your models method.
Model
public function add() {
$data = array(
'name' => $_POST['companyName']
,'type' => $_POST['companyType']
,'active' => '1');
$this->db->insert('company', $data);
$cid = $this->db->insert_id();
$data2 = array(
'cid' => $cid
,'name' => $_POST['locationName']
,'address' => $_POST['locationAddress']);
$this->db->insert('locations', $data2);
// This returns your first inserts id
return $cid;
}
Controller
public function add() {
if (isset($_POST["add"]))
{
$id = $this->Company_model->add();
redirect('company/view/'.$id);
}
...

Resources