[英]Updating content Laravel
我想在laravel(我的新功能)中為我的Web應用程序創建一個功能,使用戶的每個帖子/評論/主題(在我的情況下)都具有upVote和downVote的功能。 現在,我開始使用upVote,但是無論如何它都無法正常工作。
在視圖(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>
其中$ Theme-> name是用戶想要進行投票/點贊(無論如何)的那個。
路線:
Route::put('/', [
'uses'=>'Vote@VotePlus',
'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]);
}
};
我正在嘗試一切,但沒有用。 有人能幫助我嗎?
使用錨標記,您僅發送獲取請求。 如果要放置它,則必須創建一個表單,然后添加:
<input type="hidden" name="_method" value="PUT">
解決此問題的另一種方法是使用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', 'ThemeController@getFive');
Route::post('api/themes/voteUp, 'ThemeController@voteUp');
您的ThemeController
function getFive() {
return Theme::paginate(5);
}
function voteUp(Request $request) {
$theme = Theme::whereId($request->id);
$theme->votes += 1;
$theme->save();
return $theme;
}
此代碼未經測試。 但我認為您明白了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.