How can i copy a record and save it with a different value for 1 or more field?
for example:
get----> first_name, last_name, civil_status, work
i want to copy the first name, and last name then insert it with a new civil status and work.
You could use the replicate method of model like this:
// Retrieve the first task
$task = Task::first();
$newTask = $task->replicate();
$newTask->project_id = 16; // the new project_id
$newTask->save();
You could use replicate method. This will create a new object with the same values except the primary key, and the timestamps. After that you can save your model:
$task = Task::find(1);
$new = $task->replicate();
If you want you could change a property
$new->project = $otherProject;
and then
$new->save();
if you want the new ID, easy:
$newID = $new->id;
You can use replicate() and then update that row:
Model::find(1)->replicate()->save();
$model = Model::find(1);
$model->project_id = $new_project_id;
$model->save();
also you can do like this.
$selected = Model::find(1);
$copy = $selected->replicate()->fill(
[
'project_id' => $new_project_id,
]
);
$copy->save();
Related
What I want to do is add an object to the existing query.
This is my work in progress right now:
$users = ModelUser::where('date_created', $date)->get();
foreach($users as $user){
$obj = ['test1'=> 'val1','test2' => 'val2','test3'=> 'val3',];
$users['items'] = $obj;
}
return $users;
what I'm hoping is a result is like this.
{"username":'Username1', "Fname":'fname1', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
"username":'Username2', "Fname":'fname2', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
"username":'Username3', "Fname":'fname3', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
"username":'Username4', "Fname":'fname4', "items":['test1' = 'val1','test3' = 'val3','test3' = 'val3']
}
Where the items are like in a sub object.
Convert it into a collection and push into it
https://laravel.com/docs/9.x/collections#method-push
Just to understand a bit more, does the "items" element you want to add to the user object have any relationship at the database level?
If so, it would be better to define a relationship within the ModelUser https://laravel.com/docs/9.x/eloquent-relationships#defining-relationships
In case not, I see you're using a $user as an array, but actually $user is a ModelUser element.
So a trick, definitely not recommended, would be:
$user->items = $obj;
You can use laravel map as
$users = ModelUser::where('date_created', $date)->get();
will return a collection. So your expected code will be something like the following
$users = $users
->map(function ($user) use ($obj) {
return $user->items = $obj;
})
);
Suppose I have a model for a table in which the columns are written in Portuguese. In this way:
class Order extends Model
{
use HasFactory;
protected $fillable = [
'nota_id', 'identificacao'
];
//more..
}
Currently, to set and get values I do as follows:
$order = new Order();
$order->nota_id = 1;
$order->identificacao = '123456';
echo $order->nota_id;
echo $order->identificacao;
Rename columns directly in the table is not an option. But I need to do something like this:
$order = new Order();
$order->invoiceId = 1;
$order->identification = '123456';
echo $order->invoiceId;
echo $order->identification;
And at the end, when I save to the database using eloquent, "invoiceId" and "identification" will be converted to "nota_id" and "identificacao".
Are there any packages that solve this problem?
Your problem can be solved with laravel mutators.
Inside your model you can create mutator/accessor functions (for retrieving & setting values based on your needs) like:
getInvoiceIdAttribute($value)
{
return $this->attributes['nota_id'];
}
getIdentificationAttribute($value)
{
return $this->attributes['identificacao'];
}
Pay attention to the naming i used it's not a random name for your function. The structure must be:
get + the name you want + Attribute
Read more about laravel mutators here
Then to access them you simple do what you did in your expected behaviour:
echo $order->invoiceId;
echo $order->identification;
Here I am using laravel 5.5. My code is
$result = DB::insert('INSERT INTO .......');
Here it returns true. But how can I get inserted id? In my table id is the primary key. Thanks in advance
you can use insertGetId().
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
doc can be found here.
Instead of using DB method you can simply use Laravel eloquent:
$result = <YOUR_MODEL_NAME>::create(<YOUR_DATA>)->id();
it return the last inserted record id.
And make sure if you use this method you need to add $fillable in your MODEL like:
class <YOUR_MODEL> extends Model
{
protected $fillable = [ 'column_name_1', 'column_name_2', .., 'column_name_n' ];
}
Why don't you order your rows and get last id?
select <primary key> from <table> order by desc limit 1;
$result = MODEL_NAME::create(data);
return $result->id;
try this may be it's working
I have output object $product after inserting data into table Product:
$product = Product::create($data);
In model Product I have:
public function images()
{
return $this->hasMany("App\ProductImage");
}
The I try to add images to table product_images:
$product->images()->save(new ProductImage(UploadFiles::$files));
Relationship beetwen tables is product.id = product_images.
So, after inserting I get message:
General error: 1364 Field 'image' doesn't have a default value (SQL: insert into `product_images` (`product_id`) values (21))
OK, firstly let's deal with saving one image:
Assuming you have a product_images table with id, image, product_id, you would attach an image like so:
$image = new ProductImage(['image' => 'myImage.jpg']);
$product->images()->save($image);
Now it looks like you have an array, so you can't save that directly, you need to put it in a for loop. I don't know the format of your UploadFiles::$files, but I'll assume it's just a list of file names to save:
$files = UploadFiles::$files;
foreach($files as $file){
$image = new ProductImage(['image' => $file]);
$product->images()->save($image);
}
Alternatively, you could create the whole thing as an array and use saveMany, which would be better:
$files = UploadFiles::$files;
$productImages = [];
foreach($files as $image){
$productImages[] = new ProductImage(['image' => $image]);
}
$product->images()->saveMany($productImages);
In my project I need to find some data from sql without using id in table. For example we can use this code to find data by id:
$result = BuyCard::find(10);
but I want to search in other table column such as user_code without changing laravel stucture instead if id with other column. I've tried this:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
$data->result_transaction = 1;
$data->save();
For this code I'm getting an error but I can use it. But this code works fine:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
$data = BuyCard::find($data->id);
$data->result_transaction = 1;
$data->save();
how to edit this without using
$data = BuyCard::find($data->id);
between code? code is working fine but this is not correct.
Try to change this:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
To:
$data = DB::table('buy_card_transactions')->where(array('transaction_id' => $key))->first();
Or:
BuyCard::where('transaction_id',$key)->first();