gpt4 book ai didi

php - Laravel undefined offset 错误

转载 作者:行者123 更新时间:2023-12-04 03:11:45 25 4
gpt4 key购买 nike

我刚刚完成我的博客,使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com