我正在为University进行网络编程,正在尝试为留言簿的注释区域设置喜欢和不喜欢的功能时遇到了麻烦。
一旦不喜欢或喜欢的按钮被按下,网站上的电话号码就会自动更新一次。
我的评论可以正确显示,但是喜欢的功能已损坏,我不知道如何解决。
这是我的代码
Controller (LikesController.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LikesController extends Controller (It says my Like Controller is never used not sure why this is)
{
public function likepl (Comment, $comment) { (Says that Comment is "Undefined" also not sure why this is)
$comment -> likePlus (); (Method likePlus not found)
return redirect () -> action ('CommentController@index');
}
}
Model (comment.php)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public static function paginate(int $COMMENTS_PER_PAGE)
{
}
public function likePlus()
{
$this -> likes += 1;
$this -> update ();
}
public function dislikePlus()
{
$this -> dislikes += 1;
$this -> update ();
}
}
View Page (comment.comments)
@extends('setup')
@section('content')
<div class="container main-table">
<div class="box">
<h1 class="title">Guest book Comments</h1>
@if (count ($comments) > 5)
<table class="table is-striped is-hoverable">
<thead>
<tr>
<th>User</th>
<th>Comment</th>
<th>Date</th>
<th>Likes</th>
<th>DisLikes</th>
</tr>
</thead>
<tr>
@foreach ($comments as $c)
{{--declaring the comments--}}
<tr>
<td>{{ $c -> user }}</td>
<td>{{ $c -> comments }}</td>
<td>{{ $c -> created_at -> format ('D jS F') }}</td>
<td>{{ $c -> likes }}</td>
<td>{{ $c -> dislikes }}</td>
</tr>
<tr class="icon heart">
<td><a class="button" href="/comment/{{ $c -> id }}/like/"><ion-icon name="md-heart"></ion-icon></a></td>
<td><a class="button" href="/comment/{{ $c -> id }}/dislike/"><ion-icon name="md-heart-empty"></ion-icon></a></td>
</tr>
@endforeach
</table>
{{ $comments -> links() }} {{-- Setting pagination--}}
@else
<div class="notification is-info">
<p>
The Guest book is empty. Why not add a comment?
</p>
</div>
@endif
</div>
</div>
@endsection
我用明显的错误注释了代码,以便更好地参考。
这是我用于评论页面的路线。
Route::get('/','CommentController@index');
Route::get('/comment/{comment}/like/', 'LikesController@likePl');
Route::get('/comment/{comment}/dislike/', 'DislikesController@dislikePl');
答案 0 :(得分:1)
update()
函数无法正常使用。您要么更新属性并使用save()
函数,要么将数组传递给更新函数。
// 1.
$this->likes += 1;
$this->save();
// 2.
$this->update([
'likes' => $this->likes + 1,
]);
更新:更好的方法是使用内置的increment()
函数:
$this->increment('likes');
这样,无需事先知道喜欢的次数。
答案 1 :(得分:0)
我们可以先进行以下工作吗?
控制器内部的方法像这样接受request
公共函数likePl(请求$ request){//在此处编码}
使用其名称空间访问模型中的方法,如下所示 App \ Comment :: likePlus(),或者您也可以在方法内部简单地执行“ Comment :: likePlus()”,然后在其中导入“使用App \ Comment”之类的命名空间。 “。
有关更多信息,请参见此处Laravel models。
修复此问题将删除您当前遇到的错误。在您的likePl方法中使用“ dd($ request-> all())”来检查您是否获得了期望的值。
希望这会有所帮助...