I'm currently using Laravel observers to implement events in my project, however, I ran into some problem where the created event returns a wrong record, for example, I create a record called Like that has post_id set to 2 and user_id set to 1, so the laravel created event should return this record right? except it returns a record where post_id is set to 0 and user_id set to 1. my LikeObserver class:
class LikeObserver
{
/**
* Handle the like "created" event.
*
* @param \App\Like $like
* @return void
*/
public function created(Like $like)
{
dd($like);
$postId = $like->post_id;
Post::find($postId)->increment('likes_count');
}
}
as you can see whenever i dump the newly created record it returns this:
my LikeController class:
class LikeController extends Controller
{
public function insert(Request $request)
{
if(Like::where('user_id','1')->find($request->post_id))
{
return;
}
$like = Like::create(['post_id'=>$request->post_id,'user_id' => '1']);
}
public function remove(Request $request)
{
Like::where('user_id',auth()->user()->id)->findOrFail($request->post_id)->delete();
}
}
I pass post_id set to 2, however, Laravel returns the newly created record with post_id set to 0.
okay so apparently the fix was to use the creating event instead of the created event... this does return the correct record
public static function boot()
{
parent::boot();
static::creating(function ($like){
//returns the correct record.
dd($like);
});
}