php - Laravel undefined offset 错误

标签 php laravel

我刚刚完成我的博客,使用 laravel,我想在上面添加评论功能,但我遇到了一些这样的错误,有人可以帮助我吗??, 对不起我的英语,英语不是我的母语, 谢谢:)

(1/1) ErrorException
Undefined offset: 1

这是我的 AdminBlog.php 模型

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class AdminBlog extends Model
{
    protected $table = 'admin';
    protected $fillable = ['title','text','images','slug'];

    public function comment(){
        return $this->hasMany('App\Comment');
    }
}

Comment.php 模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $table = 'comment';
    protected $fillable = ['name','email','text','post_id'];

    public function post(){
        return $this->belongsTo('App\AdminBlog');
    }
}

博客 Controller .php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\AdminBlog;
use App\Comment;

class BlogController extends Controller
{
    //Index
    public function index(){
        $post   = AdminBlog::all();
        return view('blog/index', compact('post'));
    }

    //Show
    public function show($id){
        $post       = AdminBlog::findOrFail($id);
        $comment    = Comment::all();
        //dd($comment);
        return view('blog/show', ['post'    => $post,
                                  'comment' => $comment]);
    }
}

显示.blade.php

<div class="col-md-12 post-comment-show">
        @foreach($post->comment() as $list)
            <p>{{ $list->text }}</p>
        @foreach
</div>

最佳答案

你应该使用:

<div class="col-md-12 post-comment-show">
    @foreach($post->comment as $list)
        <p>{{ $list->text }}</p>
    @foreach
</div>

请注意,您使用了 comment()。此外,您应该为 hasMany 关系使用复数名称,因此 comment 应该是 comments

此外,在您的 show 方法中,您应该使用如下内容:

public function show($id)
{
    $post = AdminBlog::with('comment')->findOrFail($id);

    return view('blog/show', ['post' => $post]);
}

关于php - Laravel undefined offset 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44723181/

相关文章:

Laravel:如何在浏览器中查看此 S3 文件

php - 使用 PHP 输出谷歌搜索结果?

php - 逐行读取文件返回的字符串

php - 未捕获的 PHP 异常导致 500 服务器错误

php - 从 php 数组中复制一个元素

Laravel 6 Passport CSRF token 不匹配

php - 如何使用 PHP 删除重复的换行符

node.js - 无法连接到 Redis

mysql - 将原始查询转换为 Eloquent 查询

laravel - 如何获取 route 的 uri 段?