KnitZilla, the backend(ening);
In my last episode, I wrote about how I got a typescript react app to work in a Laravel stack.
In this episode, I will try to explain why I think Laravel is a cool framework, and why you might want to use it for your next full-stack project!
First of all, let's look at the model.
Laravel provides a Database agnostic tool to write your database migrations in.
For me, being mostly a frontend developer, I wrote my entire database configuration in my first migration, but you might want to do it differently.
What is cool for me, is that I do not need to know the specifics of the underlying database, I just need to maintain a higher-order overview of the model I want in my app.
And thus, my database is created. I like it! Notice that I am adding a foreign key reference to a user model in this model.
As a developer, after having created the actual persistence model we need to find a way to query our data. Again, Laravel provides an easy to use interface for such options.
With Eloquent https://laravel.com/docs/6.x/eloquent, we can tell the relations and which fields should be mutable through the model(the $fillable field). And thus, our query system is in place.
How do we then go about using it?
Well in a controller dummy!
First of all, I love how I can add which middleware chain I want to use in the constructor, and it then applies to all routes in this controller.
In the index function, which will be exposed as the get request at the root of this controller will use our eloquent data model.
Since I am using authentication in this controller, I can pull out the id of the user who made the request and then only return the projects associated with that user (In the Project eloquent model I specified a user's function).
Looking closer at the fluent API query I made, the first function chained is called
with("user"). This is how you can lazy load values on the request to the database, saving precious roundtrips. The next to parts is pretty self-explanatory.
Later, in the store function (which would map to the POST request of the root) I create a new project resource. And again leveraging that I have the current user through the context, I can safely say that it is this user that I want to add the project on.
This is just the API part of Laravel, and there are so many more cool things that you can do.
To just name a few:
- Cron jobs baked in (Task scheduling)
- Different middleware groups to different endpoints
- Full app expectation tracking
In summary, using Laravel and React has allowed me, in a very short amount of time, to create a full-stack app, where users can sign up and log in. All endpoints but authentication endpoints are protected, and the data is persisted (in my case in a MySQL database).