I like the idea of Tinkerwell. It looks very convenient when you need to execute a query or command using Laravel syntax.
Especially, I missed this when I needed to run a query on staging or production.
I do not recommend running any queries on production. In general, no one should have easy access to production. But there are situations where it really helps.
Usually, you need to log into production via SSH, find the necessary container, and, if needed, switch to the correct node.
Let's create our own script to handle this task.
Creating the script file
Create a file outside of Git, for example:
touch ./storage/framework/testing/tinko.php
With the code that you want to execute on production. For example:
<?php
$user = App\Models\User::inRandomOrder()->first();
dd($user->email);
You can run it locally very easily:
php artisan tinker tinker storage/framework/testing/tinko.php
Running it on production
To run this on production, create a script in the same folder that will execute this code:
touch ./storage/framework/testing/tinko.sh
With the following content:
#!/bin/sh
SERV=root@name-of-your-server-or-ip.com
cat ./storage/framework/testing/tinko.php | sed 's/<?php//g' | ssh -t $SERV "php artisan tinker"
What is happening here?
- We store the production server path in the
SERV
variable. - The last command takes our PHP script, removes
<?php
, and passes it for execution in Tinker via SSH.
Don't forget to give execution permissions to the script:
chmod +x ./storage/framework/testing/tinko.sh
Run the command and see the result:
./storage/framework/testing/tinko.sh
Some issues
- The full content of the file is dumped into the console.
- There is no syntax highlighting.
But these are minor issues that can be tolerated.
You can add an alias for the command to avoid typing the full path or even create a separate Run configuration in your IDE.
Running a new Docker container for the script
Sometimes, you may need to start a new Docker container to execute the script. In that case, do the following:
#!/bin/sh
SERV=root@name-of-your-server.com
COMMAND="docker run -i --rm image_name php artisan tinker"
cat ./storage/framework/testing/tinko.php | sed 's/<?php//g' | ssh -t $SERV "${COMMAND}"
Finding a container ID before execution
If you need to find the container ID before executing the script, you can use the following script:
STAGE=root@name-of-your-server.com
CONTAINER_ID=$(ssh $STAGE "docker ps --format '{{.ID}}\t{{.Image}}'" | grep -E 'app.' | awk '{print $1}' | head -n 1)
cat ./storage/framework/testing/tinko.php | \
sed 's/<?php//g' | \
ssh -t $STAGE "docker exec -i $CONTAINER_ID php artisan tinker"
Use with caution.
Top comments (0)