Hello & Happy Holidays.
My Users can follow Partners within the Test Application. I generated an Event (FollowedPartner) and a Listener(AwardPointsForFollowing), so whenever they follow a Partner, they should be awarded with x Points.
I’ve followed the concept of a “points adjustment” model with a foreign key to a user, and a polymorphic relation to a model. Then, I set up event listeners to award points based on various events.
With the following implementation the Follow functionality works (after I implemented the listener, the with('info', 'Followed') will not be shown, anymore (So something is happening)), but it won't store any points within the points_adjustments table.
points_adjustments table:
Schema::create('points_adjustments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('event');
$table->integer('points');
$table->string('model_type')->nullable();
$table->unsignedInteger('model_id')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->index(['user_id', 'points']);
});
User.php
protected $events = [
'created' => Events\FollowedPartner::class,
];
public function pointsAdjustments(){
return $this->hasMany(PointAdjustment::class);
}
public function awardPoints($event, $points, User $user){
$adjustment = new PointAdjustment([
'user_id' => Auth::user()->id,
'event' => get_class($event),
'points' => $points,
]);
$adjustment->user()->associate($user);
return $this-> pointsAdjustments()->save($adjustment);
}
PointAdjustment.php
public function user(){
return $this->belongsTo(User::class);
}
Events/FollowedPartner.php
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
Listeners/AwardPointsForFollowing.php
public function handle(FollowedPartner $event)
{
$event->followPartner()->user->awardPoints($event, 5, $event->followPartner);
}
followPartner() at User.php
public function followPartner(Partner $partner){
$this->partner()->save($partner, ['followed' => true]);
}
ProfileController (follow)
public function follow(Partner $partner, User $user){
$user = Auth::user();
$partner = Partner::where('id', $partner->id)->first();
Auth::user()->followPartner($partner);
return redirect()->route('partner.show', $partner)->with('info', 'Followed.');
}
Is there something I am not getting correctly within the setup?
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2BZkPo3
via IFTTT
Aucun commentaire:
Enregistrer un commentaire