Writing and debugging Eloquent queries with Tinkerwell

Published on by

Writing and debugging Eloquent queries with Tinkerwell image

As a Laravel developer, you are writing Eloquent queries every day. These queries can be a simple insert of a new record or a complex select with multiple relationships and dependencies. In this article we're looking into the options that Tinkerwell brings to the table to make this process easier for you.

Tinkerwell is a code runner that allows running code within the context of your application without switching to the browser all the time to test your code. When writing Eloquent queries, it allows you to run the query after every additional condition that you add to the query.

Imagine that you run an online community of happy developers that happens to have a message board and a platform for premium video courses. As a task, you want to export all users who own at least one premium course but also use the message board frequently and send them some stickers of your community.

Let's start by writing the Eloquent query on your local development environment, so that there is no risk to break production data. Navigate to the root directory of the project in Tinkerwell and open the application. Tinkerwell will automatically bootstrap your application and import all required classes, so let's start writing the query right away.

Tinkerwell works with any environment. So if you aren't using PHP directly on your system, you can connect to a Docker container, a virtual machine or even Laravel Vapor. When working with remote setups, connect via SSH and you are good to go. Later this summer, Tinkerwell will support Docker on remote environments as well.

User::count()

Now we can see that Tinkerwell has booted the app and it returns how many users we have. Let's filter them for all users who have at least one order in the database.

use App\Models\User;
 
User::whereHas('orders')->count()

Before we proceed with filtering, we can use Magic Comments of Tinkerwell, to add inline debug output to our script at runtime without changing the result of the code snippet. We can use //? at the end of a line to output the result of this line or do an inline function call with the /*?->*/ syntax.

use App\Models\User;
 
User::whereHas("orders") /*?->count()*/
->whereHas("posts")
->count(); //?

This verifies that our query works and displays how many users are left after every step.

In the next step, we're filtering the results and only include users who did not get swag in the past. On the model level, the swag column is a datetime so that we can see when they got their last delivery.

use App\Models\User;
 
User::whereNull('swag')
->whereHas("orders") /*?->count()*/
->whereHas("posts")
->count(); //?

Tinkerwell makes exporting of data to a CSV file pretty simple with the Table Mode. As long as the result of your code snippet is an array or a collection, you can display it in a table view and use the columns in the UI to sort the results.

In our example, it makes sense to export a list of users with their address and so we grab the address from their last order and map the results to a collection.

use App\Models\User;
 
User::whereNull("swag")
->whereHas("orders")
->whereHas("posts")
->get()
->map(function ($user) {
$currentAddress = $user->orders()->latest()->first();
return [
"name" => $user->name,
"street" => $currentAddress->address,
"city" => $currentAddress->city,
"postcode" => $currentAddress->postcode,
"country" => $currentAddress->country
];
});

This is the final list for our swag team and we can create an export without changing our application at all.

After we've exported the users, we'll use Tinkerwell to update them and set their latest swag delivery date to now().

use App\Models\User;
 
User::whereNull("swag")
->whereHas("orders")
->whereHas("posts")
->update([
'swag' => now()
])

After verifying that our scripts worked as expected, we can either move to run them on production directly or decide to save them as snippets first. Tinkerwell supports local snippets that you save and manage within Tinkerwell and that you can open from the Command Palette by pressing Shift + Ctrl/Cmd + P and searching for the label of the snippet or shared snippets. You can share a snippet by saving it to a .tinkerwell/snippet directory within your project and Tinkerwell loads it automatically when you connect to the application.

To run the code on your production environment and actually exporting a customer list, you can use the SSH connection manager of Tinkerwell to add a remote environment for the application. If you use Laravel Vapor, simply select the Vapor option in the sidebar and choose your production environment.

Tinkerwell makes tasks like this super easy and when you start using it regularly, you'll find dozens of other scenarios where Tinkerwell speeds up your workflow and makes coding even more enjoyable. You can simply use Laravel helpers to generate UUIDs or slugs, dispatch jobs or play around with APIs via the HTTP facade.

When you have a Tinkerwell license, you can expect monthly updates with improvements, bug fixes and new features. In the last 12 months, Tinkerwell got more than 25 updates and these updates included shared snippets, new themes, Collision support and much more.

If you don't have a Tinkerwell license yet, you can click here and use the code LARAVEL-NEWS during the checkout and get Tinkerwell with a 10% discount this week.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
No Compromises

Join the Mastering Laravel community to level up your skills and get trusted advice

Visit No Compromises
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with Vue and Livewire stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Asserting a JSON Response Structure in Laravel image

Asserting a JSON Response Structure in Laravel

Read article
Backpack turns 8 years old, celebrates with 40% discount image

Backpack turns 8 years old, celebrates with 40% discount

Read article
Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4 image

Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4

Read article
Neovim Plugin to for Navigating Laravel and Livewire Components image

Neovim Plugin to for Navigating Laravel and Livewire Components

Read article
Laravel Herd v1.7 is out with updates to the dump UI image

Laravel Herd v1.7 is out with updates to the dump UI

Read article
Share Error Package for Laravel's New Exception Page image

Share Error Package for Laravel's New Exception Page

Read article