In this episode, we get hands-on and create our very first action in Laravel! We start by reviewing the basic setup: there's a dashboard with a form for submitting a post, but currently, the form doesn't do anything. Our first step is to wire this up by setting up a controller (using Laravel's invokable controller pattern).
We go through installing the Laravel Actions package and explore how it adds a new make:action
command to Artisan. With that, we create our CreatePost
action class. The episode covers the different ways you can call an action, but we stick to the straightforward CreatePost::run()
for simplicity.
Then, we take care of form validation in the controller (using basic required rules for the body
field), making sure our app only accepts valid posts. Next, we set up the actual database model for posts, create the necessary migration, factory, and relationship with the user model. Once that's ready, we refine our action to accept a User and some data, letting us call user->posts()->create($data)
from inside the action—super clean!
To wrap up, we test it out by submitting a post through the form and confirm that it appears in the database. While using an action for this simple task might feel a bit overkill right now, you'll see the advantages (especially for testing and code organization) as the course progresses. In the next lesson, we'll look at an even cleaner way to use actions by resolving them from the container.