Final thoughts abut state machines

Usage

// e.g. inside a controller
$post = Post::find(1);
// dd($post->state); // 'draft'
$post->state()->requestReview('Joe Doe');
// dd($post->state); 'in_review'

$post->state()->requestReview('Joe Doe');
// Exception is thrown Invalid transition

Summary

  • ideal for models with states/statuses
  • when there are clear set of rules when transitioning from state to state
  • logic in one place
  • reduces bugs
  • easy to test

Credits & Source

Jake Bennett at Laracon US 2023 Nashville.
https://youtu.be/1A1xFtlDyzU?si=2FMgxoq4WiwhcycT