正在更新内容Laravel
我想在laravel(我是新手)中为我的web应用程序创建一个功能,即每个帖子/评论/主题(在我的情况下)用户有能力upVote和downVote。现在我正在用upVote开玩笑,但它并没有任何作用。正在更新内容Laravel
在视图(welcome.blade.php) 我:
<a href="{{ route('Voteplus', ['name' => $Theme->name]) }}"> <img class="media-object" style="height:40px; width:40px;" src="images/upVote.svg" alt="..."></a>
其中$主题 - >名称是用户要给予好评/像(任何)之一。
路线:
Route::put('/', [
'uses'=>'[email protected]',
'as' =>'Voteplus' //Name of route
]);
而且控制器:
<?php
namespace App\Http\Controllers;
use App\NewTheme;
use DB;
class Vote extends Controller {
public function VotePlus($name){
DB::table('New_Themes')
->where('name', $name)
->increment('upVotes', 1);
$Themes = NewTheme::paginate(5);
return redirect()->route('welcome', ['Themes'=>$Themes]);
}
};
我想要的一切,但它不工作。有人能帮助我吗?
解决此问题的另一种方法是使用Ajax。现在,每次用户想要投票选择一个主题时,该页面都会刷新,这可能非常令人沮丧。
我想你应该使用Ajax发布到后端,并在成功回调中使用javascript更新视图。我建议使用Angular作为前端。它拥有你所需要的一切,并且制作一个Ajax请求非常简单。
所以,下面是一个简单的例子,说明如何使用Angular + Laravel来使您的Web应用程序正常工作。
前端
<html ng-app="exampleApp">
<head>
<title>MyTitle</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="ThemeController">
<ul>
<li ng-repeat="theme in themes">
<span><% theme.name %></span>
<p><% theme.description %></p>
<p><% theme.votes %></p>
<a href="#" ng-click="voteUp(theme)">Vote Up</a>
</li>
</ul>
</div>
<script type="text/javascript">
var app = angular.module("exampleApp", [], function($interpolateProvider) {
// This we need to not collide with Laravel's {{ }}
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
app.controller('ThemeController', function($scope, $http) {
$scope.themes = [];
$scope.voteUp = function(theme) {
$http({
url: '/api/themes/voteUp',
method: 'POST',
data: {
id: theme.id
}
}).success(function(response) {
theme.votes += 1;
});
}
// On init we need to get the themes
$http({
url: '/api/themes',
method: 'GET'
}).success(function(themes) {
$scope.themes = themes;
});
});
</script>
</body>
</html>
后端
你的路线
Route::get('api/themes', '[email protected]');
Route::post('api/themes/voteUp, '[email protected]');
你ThemeController
function getFive() {
return Theme::paginate(5);
}
function voteUp(Request $request) {
$theme = Theme::whereId($request->id);
$theme->votes += 1;
$theme->save();
return $theme;
}
此代码未经测试。但我会认为你明白了!
我改变了一点点,它的工作原理!非常感谢你! – DomainFlag
太棒了!很高兴我能帮到 –
使用锚标签,您只发送获取请求。如果你想要它被放置,你必须创建一个表单,然后添加:
<input type="hidden" name="_method" value="PUT">
谢谢你的见解,我终于解决了这个问题:) – DomainFlag
' - > where('title',$ title)''应该是' - > where('title',$ name )'? –
我改变了,但它不起作用 – DomainFlag
也许投放路线是错误的,我使用它都是错误的? – DomainFlag