John Davidson

php - Laravel simplified save data in database by simple function

0 comments
Message:


As we know, we can save data in database by this code:


$address = new Address();
$address->user_id = $user->id;
$address->title = $request->get('title');
$address->detail = $request->get('detail');
$address->phone = $request->get('phone');
$address->address = $request->get('address');
$address->save();

here i want to simplified this action by a function such as save() for example:


save(
class: Address::class,
fields: [
'title',
'detail',
'phone',
'address',
'user_id' => 1,
]
);

function save($class, $fields): void
{
$class = new $class;
foreach ($fields as $key => $field) {
if ($key == null) {
$class->$field = get($field);
} else {
$class->$key = $field;
}
}
$class->save();
}

function get(string $key)
{
return request()->get($key);
}

after using save method i get incorrect data in attributes:


  #attributes: array:5 [
"title" => "aaaaa"
1 => "detail"
2 => "phone"
3 => "address"
"user_id" => 1
]

i don't know why in this section my function generate incorrect data with incorrect array keys for that and it should be:


  #attributes: array:5 [
"title" => "test"
"detail" => "test detail"
"phone" => "test phone"
"address" => "test address"
"user_id" => 1
]

how can i resolve save method to generate above array of data?



My Answer:
>save([
'street' => '123 Main St',
'city' => 'New York',
'state' => 'NY',
'zip_code' => '10001'
]);

_This code creates a new instance of the Address model and then saves the data to the database by calling the save() method._

_However, we can simplify this process by creating a simple function in our model class that handles the saving of data. Here's how we can do it:_

php
class Address extends Model
{
protected $fillable = ['street', 'city', 'state', 'zip_code'];

public static function saveAddress($data)
{
$address = new Address();
$address->fill($data);
$address->save();
}
}


_With this function in our Address model class, we can now save data to the database by simply calling the saveAddress() method and passing in the data as an array:_

php
Address::saveAddress([
'street' => '123 Main St',
'city' => 'New York',
'state' => 'NY',
'zip_code' => '10001'
]);


_This simplifies the process of saving data in the database and makes our code more readable and maintainable._

Rate this post

5 of 5 based on 4207 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us