Move data from one table with button to another table Laravel - php

I have found this:
Move data from one MySQL table to another
But in Laravel it's a bit different. Like him I want a button which deletes a row in a table like this one:
(Updated picture)
Just to have an example. After he hit the button it should move the shown row into the database just like it is shown here and delete it afterwards. I really don't know how to start something like this in Laravel and I really can't find something related.
Maybe this will make it more clear:
$user_input = $request->userInput
$scores = DB::table('cd')
->join('customers', 'cd.fk_lend_id', '=', 'customer .lend_id')
->select('cd.fk_lend_id','cd.serialnumber','users.name', 'cd.created_at as lend on')
->where('cd.fk_lend_id',$request->$user_input)
->get();

Suppose you have two tables: firsts and seconds
For Laravel you must have two Models for these two tables: First and Second respectively.
Now, in your controller,
//import your models
use App\First;
use App\Second;
//create a function which takes the id of the first table as a parameter
public function test($id)
{
$first = First::where('id', $id)->first(); //this will select the row with the given id
//now save the data in the variables;
$sn = $first->serialnumber;
$cust = $first->customer;
$lendon = $first->lend_on;
$first->delete();
$second = new Second();
$second->serialnumber = $sn;
$second->customer = $cust;
$second->lend_on = $lendon;
$second->save();
//then return to your view or whatever you want to do
return view('someview);
}
Remember the above controller function is called on button clicked and an id must be passed.
The route will be something like this:
Route::get('/{id}', [
'as' => 'test',
'uses' => 'YourController#test',
]);
And, your button link like:
Button

This might be a simpler way to do the Laravel "move record" part of this.
use App\Http\Controllers\Controller;
use App\Models\TableOne;
use App\Models\TableTwo;
use Illuminate\Http\Request;
class MoveOneRecord extends Controller
{
public static function move_one_record(Request $request)
{
// before code
// get id
$id = intval( $request->input('id', 0) );
// grab the first row of data
$row_object = TableOne::where('id', $id))->first();
// check if we have data
if (empty($row_object)) { throw new Exception("No valid row data."); }
// convert to array
$row_array = $row_object->toArray();
// unset the row id (assuming id autoincrements)
unset($row_array['id']);
// insert the row data into the new table (assuming all fields are the same)
TableTwo::insert($row_array);
// after code
}
}

Related

Show error message when detected duplicate entry

I wanted to let the system to show error message when detect duplicated entry of full_name column without applying unique in the full_name column from public function rules() in model.
My code is like this :
if ($model->load(Yii::$app->request->post()) ) {
$model->full_name = $model->first_name .'' . $model->last_name ;
$name = StudentInfo::find()->select('full_name')->where(['full_name'=> $model->full_name]);
if($name == $model->full_name ){
echo "<script type='text/javascript'>alert('Same student name is detected');</script>";
}
else{
$model->status ="Active";
$model->call_format = Countries::find()->select('phonecode')->where(['name'=> $model->country]);
$model->date_created = new Expression('NOW()');
$user->user_type ='student';
$user->user_name = $model->full_name;
$user->user_status = $model->status;
$user->authKey = Yii::$app->security->generateRandomString(10);
$user->accessToken = Yii::$app->security->generateRandomString(10);
$user->save();
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
}
But it shows error like :missing required parameters: id. When i apply model->save(false) ,it seems that the sql statement wont run because of duplicate entry in full_name column. How do i fix it?
Well, there is a construct exists() for such a purposes (see Yii2: check exist ActiveRecord model in database ).
if(StudentInfo::find()->where(['full_name'=> $model->full_name])->exists()){
echo "<script type='text/javascript'>alert('Same student name is detected');</script>";
}
else{...}
it generates the EXISTS query, which is faster and you don't have to load all the data from DB.
If you don't have such a column in your table, then check it by the first/last name.
change it:
$name = StudentInfo::find()->select('full_name')->where(['full_name'=> $model->full_name]);
To:
$name = StudentInfo::find()->select('full_name')->where(['full_name'=> $model->full_name])->one();
Also, if you use the select() method, to use the update() and save() or updateCounters() ... methods, you need the row ID in the same query.
Example:
->select('id') or ->select(['id', 'full_name'])
info: Multi-parameter is an array in select()
:missing required parameters: id
could mean that it couldn't find id, not by duplicate entry in full_name column. please check again
There are two problems with your code.
$name = StudentInfo::find()->select('full_name')->where(['full_name'=> $model->full_name]);
When this line is executed the $name variable will contain instance of yii\db\ActiveQuery. You want to call some method, that will actually execute your query and return result.
You can use scalar() to get the selected value. In that case the $name will contain the content of full_name column from result.
$name = StudentInfo::find()
->select('full_name')
->where(['full_name'=> $model->full_name])
->scalar();
Or you can use count() to get the number of rows that match condition. In that case you may leave out the select() method call but you will need to modify your condition
$count = StudentInfo::find()
->where(['full_name'=> $model->full_name])
->count();
if ($count > 0) {
echo "<script type='text/javascript'>alert('Same student name is detected');</script>";
} else {
// ...
}
The other problem is that you are not checking whether your $model->save() was successful. If your $model is new instance and the id attribute is auto-generated then when $model->save fails the $model->id is empty and then you are trying to redirect user to view with empty id.
Your code should look like this:
if ($user->save() && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
If the save fails because of validation the validation errors will be stored in models and if you are using ActiveForm widget the errors will be displayed. If you are not using ActiveForm you should do something to tell user that operation failed.
Since you are saving two different models you might want to consider use of transactions to prevent a situations where $user model is saved but save of $model fails.

Updating multiple id from array list with eloquent

I've passed to the controller an array of id and it is collected inside the student variable. I want to update the database column "lecture_id_FK" for each id in the array. I'm not sure as to how to use the array id to find the students. New in laravel.
Controller
public function setLecture($lecture,$student)
{
$students = student::whereIn('student_id', $student)->get();
$students->lecture_id_FK = $lecture;
$students->save();
//if i type "return $student" will produce -> ai160064,ai160065
}
The whereIn method takes an array as the second argument. You can get all students by using the explode function. Following getting all the records you want to update, you can do an update on all of them with the update method in laravel. With that you might be left with some code like the following:
public function setLecture($lecture,$student)
{
$studentIds = explode(',', $student);
return student::whereIn('student_id', $studentIds)
->update(['lecture_id_FK' => $lecture]);
}

Update data into table from dynamically created input field

I have 2 models Tour.php
public function Itinerary()
{
return $this->hasMany('App\Itinerary', 'tour_id');
}
and
Itinerary.php
public function tour()
{
return $this->belongsTo('App\Tour', 'tour_id');
}
tours table:
id|title|content
itineraries table:
id|tour_id|day|itinerary
I have used vue js to create or add and remove input field for day and plan dynamically. And used the following code in tour.store method to insert into itineraries table:
$count = count($request->input('day'));
$temp_day = $request->input('day');
$temp_itinerary = $request->input('itinerary');
for($i = 0; $i < $count; ++$i)
{
$itinerary = new Itinerary;
$itinerary->tour_id = $tour->id;
$itinerary->plan = $temp_itinerary[$i];
$itinerary->day = $temp_day[$i];
$itinerary->save();
}
And was successful in inserting the records.And applied same code in tour.store method. Instead of updating the rows, it inserted new rows to the table. What would be the best solution for this ?
For updation try this code
$itinerary = Itinerary::find($tour_id);
$itinerary->plan = $temp_itinerary[$i];
$itinerary->day = $temp_day[$i];
$itinerary->save();
The way you are using is to insert/create new records. To update you can use.
Itinerary::find($tour_id)->update(
['column_name'=> value]
);
Where find method takes a primary key of the table.
This will update your existing record. You can update as many columns as you want just pass in array update takes. You can also use save method as mentioned in other answer.
Check Laravel Update Eloquent
EDIT
$iterneary = Itenerary::where('tour_id', $tour_id)->first();
Now you can update this iterneary object to whatever you want.
this is how i did it. First saved all the tours in $tours[] array.
foreach($tours as $tour) {
$itinerary->tour()->updateOrCreate(['id'=> $tour['id']],$tour);
}
updateOrCreate because you may need to add new tours while updating. I know this doesnt answer your issue exactly but this could atleast give you an idea.

Want to delete all record as per id and then insert in laravel

I want to delete all record according to id and then insert record in same table,I tried many ways but can't find solution please help me.
Basically as per the document id i want to delete all document but it is not working.
Here is my controller code:
foreach ($receievers as $user) {
$this->shareRepo->deleteSharedDoc($resourceId);
$this->shareRepo->saveshareSharedDoc($resourceId, $user->id,$this->getCurrentUser());
}
The repository code:
function saveSharedDoc($resourceId, $sharedWith, $resourceOwnerId){
$shareDocs = new ShareDocs;
$shareDocs->resource_id = $resourceId;
$shareDocs->shared_with = $sharedWith;
$shareDocs->user_id = $resourceOwnerId;
$shareDocs->shared_on = $this->getCurrentDateTime();
$shareDocs->token = str_random(20);
$shareDocs->save();
return $shareDocs->token;
}
function deleteSharedDoc($resourceId){
$network = ShareDocs::where('resource_id','=',$resourceId);
$result=$network->delete();
return $result;
}
Please help me out
It's seems you're doing it correctly. But there are two things that you have to change.
You are calling to saveshareSharedDoc method within foreach loop to save data. but actual method name on your repo is saveSharedDoc. (there two "share" words on loop)
you can return deleted rows directly return ShareDocs::where('resource_id', $resourceId)->delete();

Saving dynamic values to another table/model using foreach in afterSave Yii

this is the my first post and I'm really confused with the below code. I'm building a gaming website (my first project using yii) and I'm using afterSave() in the model to insert data to another table because the relation is Many to Many. I'm fetching data from database then exploding it to get numbers only (so I can insert it in the other table) instead of ('2','|','3'). The problem is foreach is inserting one row instead (despite the fact it should insert more than one row) of two in my example and the inserted con_id value is always 1, I don't understand the issue here, please help me.
protected function afterSave()
{
$model1 = new GameConsole();
$con[] = explode('|', $this->con_id);
foreach($con as $row) {
$model1->game_id = $this->game_id;
$model1->con_id = $row;
$model1->save(false);
}
parent::afterSave();
}
you are saving one model over and over
you should change your code like this:
protected function afterSave()
{
$con[]= explode('|', $this->con_id);
foreach($con as $row){
$model1=new GameConsole; // this line creates new GameConsole
$model1->game_id= $this->game_id;
$model1->con_id=$row;
$model1->save(false);
}
return parent::afterSave(); // update : return it
}
and btw why are you not validating?

Categories