草庐IT

php - Laravel 5.1 undefined variable : comments

coder 2023-10-13 原文

我正在尝试构建一个评论系统,用户可以在其中对用户项目帖子发表评论。

我可以保存和显示项目,并在特定的项目页面 (/projects/{id}) 我有一个表单,用户可以在其中留下评论。我能够将评论保存在数据库中,但是当我尝试显示评论时,出现此错误 undefined variable :评论( View :/var/www/resources/views/projects/show.blade.php)。

我的文件: 评论模型:

class Comment extends Model
{
//comments table in database
protected $guarded = [];

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

// returns post of any comment
public function post()
{
    return $this->belongsTo('App\Project','project_id');
}


public $timestamps = false;
}

项目模型:

class Project extends Model
{
protected $fillable = [
'user_id',
'title',
'tags',
'summary',
'file_name',
'published_at'
];
public function User()
{
    return $this->belongsTo('App\User');
}
}

我的用户模型

class User extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['name', 'email', 'password'];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = ['password', 'remember_token'];

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

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

}

我的评论 Controller

 public function index()
{
    $comments = Comment::all();

    return view('projects.show', compact('comments'));
}

public function store()
{
    $input = Request::all();
    $comment = new Comment;
    $comment->body = $input['body'];
    $comment->on_projects = $input['project_id'];
    $comment->from_user = Auth::user()->id;
    $comment->save();
    return redirect('projects/'.$input['project_id']);

}

我的观点

@section('content')
<a href="/projects">Terug naar alle projecten</a>
<h1>Werkje: {{ $project->title }}</h1>
<h3>Gemaakt door: <a href='/student/{{ $project->User->id }}'>{{ $project->User->name }}</a></h3>
<img src="{{URL::to('/')}}/uploads/projects/{{ $project->file_name }}">
<h5>Tags: {{$project->tags}}</h5>
<hr />
<h1>Reageer</h1>

@if (Auth::check())

    <article> <!--Add comment -->

        <br/>
        {!! Form::open() !!}
        {!! form::text('body', null, ['class' => 'form-control']) !!}

        <br/>

        {!! Form::Submit('Reageer', ['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>{{ $comment->user->name }}</p>

            </article>


        @endforeach

    </article>
@else
    <p>Gelieve in te loggen om te kunnen reageren.</p>
@endif

我的路线:

// Student routes REST methode
Route::resource('student', 'StudentController');
Route::get('student/profile', 'StudentController@getProfile');

// add comment
Route::post('projects/{id}','CommentController@store');
// show comments
Route::get('projects/{id}','CommentController@index');

//Project routes REST methode
Route::post('projects/store', 'ProjectsController@store');
Route::resource('projects', 'ProjectsController');

// Authentication routes
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

// Registration routes
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');

// Password reset link request routes
Route::get('password/email', 'Auth\PasswordController@getEmail');
Route::post('password/email', 'Auth\PasswordController@postEmail');

// Password reset routes
Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');

我现在收到这个错误: undefined variable :项目( View :/var/www/resources/views/projects/show.blade.php)

最佳答案

我的 CommentController 中的 index() 函数现在是空的。

我在我的 show{id} 函数中查询我的 ProjectsController 中的评论

public function show($id)
{
    $input = Request::all();
    $project = Project::all()->load("User");

    $project_comments = DB::table('comments')
        ->select('body', 'name')
        ->where('on_projects', '=', $id)
        ->join('users', 'users.id', '=', 'comments.from_user')
        ->get();

    return view('projects.show', ['project' => Project::findOrFail($id), 'comments' => $project_comments]);

}

这就是我解决路线冲突的方法

// add comment
Route::post('projects/{id}','CommentController@store');
// add project
Route::post('projects/store', 'ProjectsController@store');
//Project routes REST methode
Route::resource('projects', 'ProjectsController');

关于php - Laravel 5.1 undefined variable : comments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277128/

有关php - Laravel 5.1 undefined variable : comments的更多相关文章

  1. ruby-on-rails - 这个 C 和 PHP 程序员如何学习 Ruby 和 Rails? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我来自C、php和bash背景,很容易学习,因为它们都有相同的C结构,我可以将其与我已经知道的联系起来。然后2年前我学了Python并且学得很好,Python对我来说比Ruby更容易学。然后从去年开始,我一直在尝试学习Ruby,然后是Rails,我承认,直到现在我还是学不会,讽刺的是那些打着简单易学的烙印,但是对于我这样一个老练的程序员来说,我只是无法将它

  2. ruby-on-rails - Rails 还是 Sinatra? PHP程序员入门学习哪个好? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭10年前。我使用PHP的时间太长了,对它感到厌倦了。我也想学习一门新语言。我一直在使用Ruby并且喜欢它。我必须在Rails和Sinatra之间做出选择,那么您会推荐哪一个?Sinatra真的不能用来构建复杂的应用程序,它只能用于简单的应用程序吗?

  3. ruby-on-rails - PHP 魔术方法 __call、__get 和 __set 的 Ruby 等价物 - 2

    我很确定Ruby有这些(等同于__call、__get和__set),否则find_by将如何在Rails中工作?也许有人可以举一个简单的例子来说明如何定义与find_by相同的方法?谢谢 最佳答案 简而言之你可以映射__调用带有参数的method_missing调用__设置为方法名称以'='结尾的method_missing调用__获取不带任何参数的method_missing调用__调用PHPclassMethodTest{publicfunction__call($name,$arguments){echo"Callingob

  4. ruby - Lisp - 是否适合网络编程/应用程序(交互式)? ruby 的方式是? php的方式是? - 2

    Lisp是否适合Web编程/应用程序(交互式),就像ruby​​和php一样?需要考虑的事情是:易于使用可部署性难度(尤其是对于编程初学者而言)(编辑)在阅读PaulGraham'sessay之后,我特别提到了CommonLisp.将是我的第一门编程语言。在这方面。这样做合适吗?我听说Clojure的宏功能不如CommonLisp的强大,这就是我尝试学习Clojure的原因。它教授编程并且非常强大。 最佳答案 Lisp是一个语系,而不是单一的语言。为了稍微回答您的问题,是的,存在用于各种Lisp方言的Web框架,例如用于Common

  5. 软件工程毕业设计课题(81)微信小程序毕业设计PHP校园跑腿小程序系统设计与实现 - 2

        项目背景和意义 目的:本课题主要目标是设计并能够实现一个基于微信校园跑腿小程序系统,前台用户使用小程序发布跑腿任何和接跑腿任务,后台管理使用基于PHP+MySql的B/S架构;通过后台管理跑腿的用户、查看跑腿信息和对应订单。意义:手机网络时代,大学生通过手机网购日常用品、外卖外卖、代取快递等已不再是稀奇的事情。此外,不少高校还流行着校园有偿工作,校园跑腿就成了大学生创业服务项目。        因为你在校园里,所以不会有进入的限制。并不是所有的外卖平台都可以随意进入校园,比如小黄和小蓝的双打外卖平台。许多大学禁止送餐进入学校,更不用说送餐进入宿舍了。这一措施使得校园服务市场的竞争相对不

  6. K8s部署PHP项目 - 2

    前言    前端时间PHP项目部署升级需要,需要把Laravel开发的项目部署K8s上,下面以laravel项目为例,讲解采用yaml文件方式部署项目。一、部署步骤1.创建Dockerfile文件Dockerfile是一个用来构建镜像的文本文件,在容器运行时,需要把项目文件和项目运行所必须的组件安装其中。#基础镜像FROMphp:7.4-fpm#时区ARGTZ=Asia/Shanghai#更换容器时区RUNcp"/usr/share/zoneinfo/$TZ"/etc/localtime&&echo"$TZ">/etc/timezone#替换成阿里apt-get源RUNsed-i"s@http

  7. ruby-on-rails - PHP 开发人员学习 Ruby 和 Ruby on Rails - 2

    关闭。这个问题不符合StackOverflowguidelines.它目前不接受答案。要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于StackOverflow来说是偏离主题的,因为它们往往会吸引自以为是的答案和垃圾邮件。相反,describetheproblem以及迄今为止为解决该问题所做的工作。关闭9年前。Improvethisquestion我对学习Rails很感兴趣已经有一段时间了,我觉得现在正是浸入其中并实际动手实践的好时机。在过去的一周里,我阅读了所有我能找到的关于Ruby和RubyonRails的免费电子书。我刚刚读完RubyEssentials。我也一直在玩htt

  8. ruby-on-rails - Ruby 相当于 PHP 的 ucfirst() 函数 - 2

    在Ruby中(使用Rails,如果相关)将字符串首字母大写的最佳方法是什么?请注意String#capitalize不是我想要的,因为除了将字符串的首字母大写外,此函数还使所有其他字符变为小写(这是我不想要的——我想让它们保持原样):>>"aA".capitalize=>"Aa" 最佳答案 在Rails中你有String#titleize方法:"测试字符串标题化方法".titleize#=>"测试字符串标题化方法" 关于ruby-on-rails-Ruby相当于PHP的ucfirst()

  9. ruby-on-rails - Rails 5.1 使用 RSpec 配置内置系统测试 - 2

    看完RailsConfvideoonActionDispatch::systemTestCase,我很高兴将它整合到我当前的应用程序中。目前我们的测试套件设置使用以下内容:rspecfactory_girlcapybara#功能规范database_cleaner#用于功能规范,主要用于测试jsselenium-webdriver#功能规范capybara-webkit#功能规范很难让配置适用于我们当前的设置,但我们最终成功了,这在很大程度上要归功于AvdiGrimm的一篇文章,标题为:Configuringdatabase_cleanerwithRails,RSpec,Capybar

  10. php - Ruby 和 PHP HMAC 不一致 - 2

    我尝试在Ruby中创建一个HMAC,然后在PHP中验证它。ruby:require'openssl'message="A522EBF2-5083-484D-99D9-AA97CE49FC6C,1234567890,/api/comic/aWh62,GET"key="3D2143BD-6F86-449F-992C-65ADC97B968B"hash=OpenSSL::HMAC.hexdigest('sha256',message,key)phashPHP:对于Ruby,我得到:20e3f261b762e8371decdf6f42a5892b530254e666508e885c708c5b

随机推荐