115
113

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 5 years have passed since last update.

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

Last updated at Posted at 2018-09-07

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

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

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()とかもあります

参考

おわり

以下もどうぞ

115
113
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
115
113

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?