2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel 【入門】 withErrorsの使い方

Last updated at Posted at 2021-10-31

はじめに

withErrorsで処理失敗時のエラーメッセージを出力する例をいくつか挙げています。
withErrorsはエラーが発生したら、セッションにエラーメッセージをフラッシュデータとして保存し、エラー表示をさせる事ができます。

目次

  1. 例外処理のエラーハンドリング
  2. CRUD処理失敗時
  3. バリデーション失敗時

例外処理のエラーハンドリング

public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            // 何らかのDB登録処理
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return redirect()->back()->withErrors('エラーが発生しました');
        }
        return view('index');
    }

CRUD処理失敗時

public function destroy(Post $post)
    {
        return $post->delete()
          ? redirect()->action([PostController::class, 'index'])->with('flash_message', '投稿の削除が成功しました。')
          : redirect()->action([PostController::class, 'index'])->withErrors('投稿の削除に失敗しました。');
    }

バリデーション失敗時

public function post(Request $request)
    {
        $validator = $this->post_validator($request->all());
        if ($validator->fails()) {
                         // バリデーション失敗時
            return redirect('index')
                ->withErrors($validator)
                ->withInput();
        } else {
            // バリデーション通過後の処理
        }
    }
protected function post_validator(array $data)
    {
        return Validator::make($data, [
            'content' => ['required']
        ]);
    }
2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?