简体   繁体   中英

How can I check all data if not error then update into database with Laravel

Hi I want to check all data if id don't have any error then I want to update data

dd($data) output like this :

0 => array:3 [▼
    "id" => "1"
    "target" => "100"
  ],
1 => array:3 [▼
    "id" => "2"
    "target" => "200"
]


    for ($i = 0; $i < count($data); $i ++)
    {
        $user = User::findOrfail($data[$i]['id']);
        $user->target = $data[$i]['target'];
        $user->save();
    }

I want to do some thing like this

    for ($i = 0; $i < count($data); $i ++)
    {
        $user = User::findOrfail($data[$i]['id']);
        if(!user) {
            die('somethings error');
        }
    }

    for ($i = 0; $i < count($data); $i ++)
    {
        $user = User::findOrfail($data[$i]['id']);
        $user->target = $data[$i]['target'];
        $user->save();
    }

As you see in these way every work first loop It will check all $user then It will loop to update user again but I think this is the bad way to use 2 for loop at the same variable . How can I do some thing like this with nice code

Have you tried combining the two into one:

for ($i = 0; $i < count($data); $i ++)
{
    // use just find as it returns null, findOrFail will throw an exception if the user is not found
    $user = User::find($data[$i]['id']);
    if(!user) {
        // you can use continue; which will skip the current iteration, and collect the errors.
        die('somethings error');
    }
    // this code will not execute if the user is not found
    $user->target = $data[$i]['target'];
    $user->save();

}
$user = User::findOrfail($data[$i]['id']);

This will throw a Illuminate\\Database\\Eloquent\\ModelNotFoundException if the model isn't found, so your first loop is not needed.

So you can use only the secound loop without any problems.

If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods

See here: Laravel Documentation

Please keep in mind that eiter die or the ModelNotFoundException stop the loop. So every array element after the first die wouln't be updated.

I believe using transactions is the way to go. All the other answers till now are correct, but they DO save the users before the error happens. It seems to me that you wanna make sure all the data is valid before even saving one of the users.

you begin the transaction, go your usual way of saving users, and if an error happens, just throw an exception and rollback all the saved user.

DB::beginTransaction();
try{
  for ($i = 0; $i < count($data); $i ++)
    {
      $user = User::findOrfail($data[$i]['id']);
      if (!$user){
        throw new Exception();
      }
      $user->target = $data[$i]['target'];
      $user->save();
    }
  DB::commit();
} catch(Exception $e){
  DB::rollback();
}

What you're looking for is validation. You should validate all user-submitted data before acting upon, to check it's in the format you're expecting and doesn't contain any invalid values.

You can perform validation in a form request class. These are special request instances that you can add to your controller actions and will run before your actions. If validation fails, the user is redirected back with error messages before your controller action is ran.

You can read more about form request validation on the official Laravel documentation: https://laravel.com/docs/master/validation#form-request-validation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM