Help us understand the problem. What is going on with this article?

Laravel:$loopによるループ変数の使用例

More than 1 year has passed since last update.

繰り返し専用のループ変数($loop)

\$loopという繰り返しディレクティブの変数が用意されているので条件識別と連動させて処理する

//最初の繰り返しかどうか
$loop->first

//最後の繰り返しかどうか
$loop->last

//現在の繰り返し数(1から開始)
$loop->iteration

//あと何回繰り返すか(残り回数)
$loop->remaining

//繰り返しで使っている配列の要素数
$loop->count

//繰り返しのネスト数
$loop->depth

//ネストしている場合、親の繰り返しのループ変数を示す
$loop->depth

使用例

\$dataの数だけデータをリスト形式で表示するコード
ループ内でも初めのループ・最後のループを検知して、その時のみ文字を出力している

resources/views/hello/index.blade.php
<html>
<head>
    <title>Request&Response</title>
    <style>
        body {
            font-size:16pt;
            color:#999;
        }
        h1 {
            font-size:100pt;
            text-align: right;
            color:#eee;
            margin:-40px 0 -50px 0;
        }
    </style>
</head>
<body>
    <h1>Blade/Index</h1>
    <p>foreachディレクティブの例</p>
        @foreach($data as $item)
            //最初の繰り返しかどうか
            @if($loop->first)
            <p>※データ一覧</p><ul>
            @endif
            //現在の繰り返し数(1から開始)
            <li>NO,{{$loop->iteration}}.{{$item}}</li>
            //最後の繰り返しかどうか
            @if($loop->last)
            </ul><p>ここまで</p>
                @endif
        @endforeach

</body>
</html>
app/Http/Controllers/HelloController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;


class HelloController extends Controller
{
    public function index() {
        $data = ['one','two','three','four','five'];
        return view('hello.index',['data'=>$data]);
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした