【发布时间】:2015-10-24 20:57:26
【问题描述】:
Edit3:可能是因为两个控制器都指向同一个页面吗?
Edit2:得到答案后仍然无法正常工作。
编辑:错误一已解决,现在我得到:
未定义变量:项目(查看: /var/www/resources/views/pages/showProject.blade.php)
这可能是因为两个变量都指向同一个页面吗?项目变量在评论系统之前运行良好。
public function index()
{
$projects = Project::all();
return view('pages.projects', compact('projects'));
}
项目变量声明。
我正在尝试从我的数据库中获取我的 cmets,以显示在我正在处理的 laravel 5 项目中的特定“项目页面”上。这个想法是用户可以添加艺术项目,其他用户可以对其发表评论,但每当我尝试访问该页面时,我都会得到 p>
未定义变量:cmets(查看: /var/www/resources/views/pages/showProject.blade.php)
这是我的控制器
public function index()
{
$comments = Comment::all();
return view('pages.showProject', compact('comments'));
}
public function store()
{
$input = Request::all();
$comment = new Comment;
$comment->body = $input['body'];
$comment->project_id = $input['project_id'];
$comment->user_id = Auth::user()->id;
$comment->save();
return redirect('projects/'.$input['project_id']);
}
这些是我的路线
// add comment
Route::post('projects/{id}','CommentController@store');
// show comments
Route::post('projects/{id}','CommentController@index');
我的看法
@if (Auth::check())
<article> <!--Add comment -->
<br/>
{!! Form::open() !!}
{!! form::text('body', null, ['class' => 'form-control']) !!}
<br/>
{!! Form::Submit('Post Comment', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::hidden('project_id', $project->id) !!}
{!! Form::close() !!}
<br/>
</article>
<article>
@foreach ($comments as $comment)
<article>
<p>Body: {{ $comment->body }}</p>
<p>Author: {{ $comment->user->name }}</p>
</article>
@endforeach
</article>
@else
<p>Please log in to comment</p>
@endif
模型
class Comment extends Model
{
//comments table in database
protected $guarded = [];
// user who has commented
public function author()
{
return $this->belongsTo('App\User','user_id');
}
// returns post of any comment
public function post()
{
return $this->belongsTo('App\Project','project_id');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public $timestamps = false;
}
有什么办法可以解决这个问题吗?
提前致谢
【问题讨论】:
-
试试
return view('pages.showProject', array('comments'=>$comments)); -
'表达式结果未使用'和'无法到达的语句'在返回视图的 $cmets 部分。我会用我的模型更新 OP。
-
另外
Route::post('projects/{id}','CommentController@index');应该是Route::get('projects/','CommentController@index');//id没有被使用,你使用的是GET而不是POST -
好吧,那是我的错。我替换了它,现在错误显示“未定义变量:项目(视图:/var/www/resources/views/pages/showProject.blade.php)”。这可能是因为 cmets 和 projects 变量都指向同一个页面吗?
-
将项目变量作为关联数组添加到视图中,如 cmets
(array('project'=>Project::where('id', '=', $id)->firstOrFail()))并在控制器中从请求中获取 $id(function index($id),使用 url 中的 id 更改路由(Route::get('projects/{id}','CommentController@index');)