I almost finished my website, just one more feature to finish and this is so the user can like just once a post/theme/discussion point(whatever).
I have the table new_theme_user:
1 id
2 id_user(integer)
3 id_theme(integer)
4 upVote(tinyint)
So this is the controller:
class Vote extends Controller {
public function VoteTheme($id, $vote){
$Vote = DB::table('New_Theme_User')->where([
['id_theme', '=', $id],
['id_user', '=', Auth::id()],
])->get(); (1!!!)
if (!isset($vote)) { (2!!!)
if ($vote === 'plus')
DB::table('New_Theme_User')->insert([
['id_theme' => $id, 'id_user' => Auth::id(), 'upVote' => 1],
]);
else
DB::table('New_Theme_User')->insert([
['id_theme' => $id, 'id_user' => Auth::id(), 'upVote' => 0],
]);
if ($vote === 'plus') {
DB::table('New_Themes')
->where('id', $id)
->increment('upVotes', 1);
} else {
DB::table('New_Themes')
->where('id', $id)
->increment('downVotes', 1);
}
}
$Themes = NewTheme::paginate(5);
return redirect()->route('welcome', ['Themes'=>$Themes]);
}
};
1!!! - Is the select query which creates an object(in order to find in database if someone has already voted before the theme/post which he wants to vote again.
2!!! - Is the if statement, if the object doesn't have the values - this means the user can vote once so it populates the DB with information.
The problem: I can't figure how to work around the (2!!!), I tried isset, empty, whatever else I could find on internet, it doesn't work, even if the user voted once more the if goes through and it seems I can't find a solution. Every given help, I will greatly appreciate. Thank you!
NewThemeUser
model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class NewThemeUser extends Model
{
protected $table = 'new_theme_user';
}
Now in controller you can do like this
App\NewThemeUser::firstOrCreate(['id_theme' => $id, 'id_user' => Auth::id()])->increment($upVotes ? 'upVotes' : 'downVotes');//This will fetch the first record if there any exists for the user then increment if $upVotes then the column to increment is upVotes else upVotes