LoginSignup
108

More than 3 years have passed since last update.

posted at

updated at

【Laravel】Laravelでよく使うroute()とview()とredirect()まとめ

画面遷移系の関数でちょくちょくこんがらがるのでまとめときます

例としてここでのルーティングは以下の通りです

web.php
Route::resource('users', 'UsersController');

route()

View側でURLを指定するときに使用

<!-- 省略 -->
<a href="{{ route('users.edit', ['id' => $user->id]) }}">編集する</a>
<form method="POST" action="{{ route('users.destroy', ['id' => $user->id]) }}">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}
    <button type="submit" onclick="return window.confirm('削除しますか?');">
        <span>削除する</span>
    </button>
</form>
<!-- 省略 -->

view()

Controllerで特定のViewを表示させたいときに使用

UsersController.php
    public function edit($id)
    {
        return view('user.edit', ['user' => User::find($id)]);
    }

表示させるときに変数を定義してViewに渡すことができる

user/edit.blade.php
@if (!empty($user->name))
    {{ $user->name }}
@endif

redirect()

Controllerで特定のページへリダイレクトさせたいときに使用

以下例

UsersController.php
    public function destroy($id)
    {
        $user = User::find($id);

        // 処理やら

        if ($user->delete()) {
            return redirect('/top')->with('message', '削除しました。');
        }
        return redirect('/top')->with('message', 'エラー');
    }

with()を付けとくと遷移先でメッセージなどを表示させることができる

index.blade.php
@if (Session::has('message'))
    <p>{{ session('message') }}</p>
@endif

ほかにwithInput()とかもあります

参考

おわり

以下もどうぞ

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
What you can do with signing up
108