In this blog post, I want to share one of my daily use cases with Tinkerwell. Of course, tinkering with random code is perfect with it–but there is a lot more where Tinkerwell can help you in your daily workflow.
Querying your database
Before I had Tinkerwell, I was using Table Plus a lot. I was using it to quickly inspect some database tables or to perform some more complicated queries to get more insights of my application.
With Tinkerwell this has become a lot easier! I no longer need to write the SQL queries myself but I can use the powerful API from Laravel and eloquent to help me get the data that I need.
Let me give you an example.
In my video course platform, I have a user model. And each user has a hasMany relationship to courses.
Now I want to count all users that have access to a specific course by using the course name.
How would you do that in SQL? You would probably create a join on the users, the courses and the intermediate table and get all users where the name of the course you want to look up matches the required course name.
The resulting query might look like this:
Well... that certainly works, but it's not that fun to write.
With Tinkerwell this becomes a lot easier - and more readable. Since tinkerwell allows you to run code snippets securely via ssh on your remote servers, you can connect to your application server and the complex query suddenly just becomes:
User::whereHas("courses", function ($query) {
$query->where("title", "PHP Package Development");
})->count();
Or even simpler, since my Course model has a "belongsToMany" relationship to users, I can do:
Course::where("title", "PHP Package Development")
->first()
->users()
->count();
And here's how that looks inside Tinkerwell:
Now the benefit of tinkerwell doesn’t stop here. It just starts at this point. Once you have your query ready, you will get an eloquent collection instance, that allows us to do even more things with our selected users.
We now have full control of the user models and therefore can use both PHP and Laravel built-in features.
Let’s say your user model has a custom accessor - no problem with Tinkerwell. Since you’re dealing with your application models, you can make use of all your custom application logic.
In general, I’ve used tinkerwell a lot for these kinds of tasks - simple database queries, where having the eloquent api is a lot more intuitive and easier than having to write the SQL queries myself.
I’ll share more use cases and real-world examples in an upcoming blog post.
Do you want to get your use case featured? Let us know how you are using tinkerwell and send us a mail to [email protected]