猿问

Laravel“为 foreach() 提供的参数无效”

我正在学习 laravel,更新标签代码后标签出现问题。当我点击标签时,我遇到了这个问题:

Facade\Ignition\Exceptions\ViewException 为 foreach() 提供的参数无效(视图:C:\blog\resources\views\articles\index.blade.php)

我在控制器中的代码:

<?php


namespace App\Http\Controllers;


use App\Article;

use App\Tag;


use Illuminate\Http\Request;


class ArticlesController extends Controller

{

public function index()

{

    if(request('tag'))

    {

        $articles = Tag::where('name', request('tag'))->firstOrFail()->articles;

    } 

    else 

    {

        $articles = Article::latest()->get();

    }

    return view ('articles.index',['articles' => $articles]);

}

展示页面


@foreach ($articles as $article )

            <div class="content">

                <div class="title">

                    <h2>

                        <a href="/articles/{{$article->id}}">

                            {!! $article->title !!}

                        </a>

                    </h2>

                </div>


                <p>

                <img src="/images/banner.jpg" alt="" class="image image-full"/>

                </p>


                {!! $article->exceprt!!}

            </div>

        @endforeach

这是雄辩的标签:


<?php


namespace App;


use Illuminate\Database\Eloquent\Model;


class Tag extends Model

{

public function article()

{

    return $this->belongsToMany(Article::class);

}

}


慕慕森
浏览 200回答 2
2回答

HUX布斯

该错误表明文章数组为空。您需要添加条件来检查数组是否为空。@if(!empty($articles))@foreach ($articles as $article)@endforeach@endif这不是获取文章的正确方法。我建议你使用 whereHas 检查标签。

Cats萌萌

您articles在标签模型中的关系未定义。因此,当您打电话时,Tag::where('name', request('tag'))->firstOrFail()->articles您得到的不是 Collection 而是null.这就是您收到此错误的原因,因为您无法循环访问null变量。你应该修复你的关系:public&nbsp;function&nbsp;articles()&nbsp;//&nbsp;<----&nbsp;You&nbsp;were&nbsp;missing&nbsp;the&nbsp;'s'{&nbsp;&nbsp; &nbsp;&nbsp;return&nbsp;$this->belongsToMany(Article::class); }
随时随地看视频慕课网APP
我要回答