Reputation: 349
I am implementing a voting system in my laravel school project, it will be an online school platform where students can upload projects and other students can vote on the published content.
Somehow what I have done isn't working... Here is my code so far, hope someone can help me, and maybe help me on the way how to show the number of votes on a project.
This is my database migration:
Schema::create('votes', function($table){
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('project_id')->unsigned();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('project_id')->references('id')->on('projects');
});
My Model:
Class Vote extends Eloquent{
public function user(){
return $this->belongsTo('User');
}
public function project(){
return $this->belongsTo('Project');
}
}
My view:
@foreach ($projects as $project)
<li class="medium-4 columns">
<div class="canvas-medium">
<img src="{{ $project->image }}">
</div>
<p class="title">{{ $project->name }}</p>
<p class="owner">By
<a href="profile/{{ $project->user_id }}">{{ $project->user->firstname }} {{ $project->user->name }}</a>
<a href="/vote/{{ $project->id }}">Vote</a>
</p>
</li>
@endforeach
My controller:
class VoteController extends BaseController{
public function vote($id){
$vote = new Vote;
$vote->user_id = Auth::id();
$vote->project_id = $id;
$vote->Save();
return Redirect::to('/projects');
}
}
Routes.php:
Route::get('/projects', 'ProjectController@showall');
Route::get('/projects/vote/{id}', 'VoteController@vote');
Upvotes: 2
Views: 4787
Reputation: 6393
change
<a href="/vote/{{ $project->id }}">Vote</a>
to
<a href="/projects/vote/{{ $project->id }}">Vote</a>
p.s. if you have no validation in place and if you didn't setup a unique index in database with project id and user id, a student can vote multiple times for one particular project.... which you probably you won't want perhaps?
Route::get('/projects', 'ProjectController@showall');
will show all projects.
if you want to get the detail for each of the project, you will have to do:
Route::get('/projects/{id}', 'ProjectController@showone')
return DB::table('vote')->where('project_id','=',$id)->get();
if you want to show each vote count for every project, then it will be little bit complicated but here's this.
return DB::table('project AS p')->select([DB::raw('@project:=p.id'),
DB::raw('(SELECT COUNT(id) FROM votes AS v WHERE v.project_id = @project) AS votes'),
])->paginate(30); //or get()
Upvotes: 5
Reputation: 10104
I would eschew adding the link by route, and link it by controller instead:
<a href="{{ URL::action('VoteController@vote', [$project->id]) }}">Vote</a>
When viewing the page, the URL will appear as "http://example.com/projects/vote/1", for example. Also, if you change your route as follows:
/projects/vote/{id}
/projects/{id}/vote
Your link will be automatically changed to use the new route to that controller.
Upvotes: 1