Home > Blockchain >  Laravel simplified save data in database by simple function
Laravel simplified save data in database by simple function

Time:08-30

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?

CodePudding user response:

problem solved by checking array key by getType thanks to @jstech

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

CodePudding user response:

Try this code

new Address([
    'user_id' => $user->id,
    'title' => $request->title,
    'detail' => $request->detail,
    'phone' => $request->phone,
    'address' => $request->address,
]);
  • Related