我正在學習 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 檢查標簽。

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); }
- 2 回答
- 0 關注
- 232 瀏覽
添加回答
舉報
0/150
提交
取消