亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel“為 foreach() 提供的參數無效”

Laravel“為 foreach() 提供的參數無效”

PHP
慕慕森 2023-04-02 14:59:53
我正在學習 laravel,更新標簽代碼后標簽出現問題。當我點擊標簽時,我遇到了這個問題:Facade\Ignition\Exceptions\ViewException 為 foreach() 提供的參數無效(視圖:C:\blog\resources\views\articles\index.blade.php)我在控制器中的代碼:<?phpnamespace 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這是雄辯的標簽:<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Tag extends Model{public function article(){    return $this->belongsToMany(Article::class);}}
查看完整描述

2 回答

?
HUX布斯

TA貢獻1876條經驗 獲得超6個贊

該錯誤表明文章數組為空。


您需要添加條件來檢查數組是否為空。


@if(!empty($articles))

@foreach ($articles as $article)

@endforeach

@endif

這不是獲取文章的正確方法。我建議你使用 whereHas 檢查標簽。


查看完整回答
反對 回復 2023-04-02
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

articles在標簽模型中的關系未定義。因此,當您打電話時,Tag::where('name', request('tag'))->firstOrFail()->articles您得到的不是 Collection 而是null.

這就是您收到此錯誤的原因,因為您無法循環訪問null變量。

你應該修復你的關系:

public function articles() // <---- You were missing the 's'{  
  return $this->belongsToMany(Article::class);
}


查看完整回答
反對 回復 2023-04-02
  • 2 回答
  • 0 關注
  • 232 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號