Supercharge Your Laravel Development and Get AI to Understand Your Models
Hey there, Laravel enthusiasts! Today, I’m diving into a nifty trick that’ll make getting AI to understand your Laravel model structures a breeze. We’ll harness the power of bash scripting and AI to analyze our migrations quickly and efficiently. Let’s get started!
The Problem: Getting AI to Return Code For your Project Setup Easily
As our Laravel projects grow, so does the complexity of our database structures. Migrations pile up, relationships intertwine, and before you know it, you’re drowning in a sea of Schema::create
and up
functions. Wouldn’t it be great to get a bird’s-eye view of our models without manually sifting through dozens of files? What if you could get AI to understand your Laravel project without adding every file to the chat window?
The Solution: Bash + AI = Developer’s Best Friend
Here’s where our dynamic duo comes in a clever bash one-liner and your favorite AI chat tool (like ChatGPT or Claude). We’ll use bash to extract the relevant parts of our migrations and then feed that information to an AI for analysis and insights.
Step 1: The Magical Bash One-Liner
Here’s the one-liner code to copy and paste:
for file in *.php; do echo -e "\n\`\`\`\n${file%.*}:\n\`\`\`\n"; sed -n '/Schema::create/,/^ }/p' "$file"; echo -e "\n\`\`\`"; sed -n '/public function up/,/^ }/p' "$file" | sed '1d;$d'; echo -e "\`\`\`\n"; done
First, let’s break down our bash sorcery to understand what’s going on in an easier-to-read format:
for file in *.php; do
echo -e "\n\`\`\`\n${file%.*}:\n\`\`\`\n"
sed -n '/Schema::create/,/^ }/p' "$file"
echo -e "\n\`\`\`"
sed -n '/public function up/,/^ }/p' "$file" | sed '1d;$d'
echo -e "\`\`\`\n"
done
Just add | pbcopy to have it copied directly to your clipboard on Mac:
for file in *.php; do echo -e "\n\`\`\`\n${file%.*}:\n\`\`\`\n"; sed -n '/Schema::create/,/^ }/p' "$file"; echo -e "\n\`\`\`"; sed -n '/public function up/,/^ }/p' "$file" | sed '1d;$d'; echo -e "\`\`\`\n"; done | pbcopy
This command does the following:
- Loops through all PHP files in the current directory
- Extracts the
Schema::create
function contents - Extracts the
up
function contents (minus the function declaration) - Formats the output with the filename and proper Markdown code blocks
Step 2: Running the Command
- Open your terminal and navigate to your Laravel project’s migrations directory.
- Copy the bash one-liner above.
- Paste it into your terminal and hit Enter.
- Watch as it generates a nicely formatted output of your migrations!
Step 3: Feeding the Output to AI
Please copy the entire output from your terminal and paste it into your AI chat of choice with your preferred prompt. I usually start with this prompt:
"Analyze these Laravel migrations and understand the database and model structure, including relationships. For all conversations in this chat, refer to these migrations:"
{output here}
Generate a diagram
Here are some additional prompts you can optionally pair with the output to extract valuable insights and improvements:
- “Identify any potential relationships between these models based on the migrations.”
- “Suggest improvements or potential issues in this database design.”
- “Take this example of JSON output and generate the code to create the [model name] with its relations.”
The Benefits: Why This Approach Rocks
- Time-saver: No more manual searching through migration files or copying content manually or individually.
- Comprehensive view: Get a complete picture of your database structure in one go.
- AI-powered insights: Leverage AI to spot patterns, suggest optimizations, explain complex relationships, and generate code faster.
- Learning tool: Great for understanding legacy projects or onboarding new team members.
Wrapping Up
There you have it, folks! With this simple bash one-liner and the power of AI, you can transform how you analyze and understand your Laravel database structures and output code. Give it a try on your next project, and watch your productivity soar!
Remember, tools like these are meant to augment your skills, not replace them. Always review AI suggestions critically and trust your developer instincts.
How to Move Files by Partial File Name to New Directory on Mac using a shell script
Streamline Your Photo Editing Workflow: How to Use a Shell Script to Prioritize Selected Images
When it comes to photo editing, efficiency is key. Recently, I faced a challenge where a subject picked out 100 priority photos from a larger batch. Given the sheer number of images, manually sorting them wasn’t practical. All pictures from my SLR were named in the DCIM_# format, so I noted the last five numbers of the selected files. To streamline the process, I wrote a shell script that automatically moves the chosen files to a new folder, allowing me to focus on the priority images first. I’m sharing this script to help others enhance their photo editing workflow.
Step-by-Step Instructions on How to Run a Shell Script
Create the Shell Script:
- Open your favorite text editor (e.g., VSCode, Sublime Text, or even a basic text editor like Notepad).
- Write or paste your shell script. Here’s a simple example for moving selected files:
#!/bin/bash
# Directory containing the files
DIR="{Path}"
# Subfolder to move matching files to
TO_PROCESS_DIR="${DIR}/To Process"
# Ensure the "To Process" directory exists
mkdir -p "$TO_PROCESS_DIR"
# List of substrings to check
substrings=(
06340 06422 06500 06518 06521 06524 06539 06542 06545 06548 06553 06581
06584 06587 06608 06611 06617 06629 06649 06662 06980 06695 06733 06734
06737 06740 06743 06758 06761 06767 06773 06779 06787 06788 06791 06794
06797 06815 06818 06821 06845 06878 06890 06898 06899 06941 06947 06959
06962 06965 06970 06971 06977 06985 06986 07009 07040 07055 07062 07068
07074 07080 07083 07086 07089 07092 07097 07101 07104 07107 07113 07119
07128 07143 07146 07182 07185 07188 07191 07197 07200 07215 07218 07221
07230 07291 07302 07323 07329 07332 07338 07350 07356 07359 07476 07362
07365 07368 07389 07413 07435 07431 07461 07497 07500 07503 07506 07509
07512 07518 07524 07527 07530 07536 07542 07548 07557 07578 07584 07593
)
# Debugging: Check if the directory exists
if [ ! -d "$DIR" ]; then
echo "Directory $DIR does not exist."
exit 1
fi
# Debugging: Check if there are files in the directory
if [ -z "$(ls -A "$DIR")" ]; then
echo "No files found in the directory $DIR."
exit 1
fi
# Loop through all files in the directory
for file in "$DIR"/*; do
filename=$(basename "$file")
echo "Processing file: $filename"
moved=false
for substring in "${substrings[@]}"; do
if [[ "$filename" == *"$substring"* ]]; then
echo "Found substring '$substring' in file: $filename"
# Move the file to the "To Process" directory
mv "$file" "$TO_PROCESS_DIR"
moved=true
break
fi
done
if [ "$moved" = false ]; then
echo "No matching substring found in file: $filename"
fi
done
Save the Script:
- Save the file with a
.sh
extension, for example,move_photos.sh
.
Make the Script Executable:
- Open a terminal window.
- Navigate to the directory where your script is saved using the
cd
command. For example:cd /path/to/your/script
- Make your script executable by running:
chmod +x move_photos.sh
Run the Script:
- Still in the terminal, run your script by typing:
./move_photos.sh
Verify the Results:
- Check the destination directory to ensure that the files have been moved successfully.
Additional Tips:
- Editing the File List: Modify the
FILES
array in the script to include the specific last five digits of the filenames you want to move. - Updating Directories: Ensure that the
SOURCE_DIR
andDEST_DIR
variables are set to the correct paths on your system.
By following these steps, you can efficiently manage and prioritize your photo editing tasks, saving valuable time and effort. This shell script can be customized and expanded to suit various file management needs, making it a versatile tool in your workflow.
How to enable MacFuse/PCloud Drive on Mac Sonoma 14.2.1
I recently upgraded to Mac Sonoma 14.2.1 and MacFuse stopped loading which affected my ability to load PCloud and NTFS drives. I spent a few days trying to troubleshoot everything and in the end it turned out I had to disable Mac System Integrity Protection to get everything to load. I’m sharing in case it helps anyone else.
To disable SIP on your Mac Sonoma for extensions like MacFuse and pCloud Drive:
- Shut down your Mac: Turn off your Mac completely by pressing and holding the power button until the screen goes black.
- Restart in Recovery Mode: Enabling Recovery Mode depends on your Mac. You can try the steps below or follow Apple’s guide here.
Power on your Mac and immediately press and hold Command (⌘) + R to enter Recovery Mode.
Power on your Mac and hold the power button down until Other Options displays. - Open Terminal: In Recovery Mode, select “Utilities” in the macOS Utilities window and select “Terminal.”
- Disable SIP: Type
csrutil disable
in Terminal and press Enter. This disables System Integrity Protection (SIP). - Restart Mac: Click the Apple menu and select “Restart” to reboot your Mac with SIP disabled.
- Re-enable SIP (if needed): Follow the same steps but use
csrutil enable
in Terminal to re-enable SIP.
Note: Disabling SIP poses security risks. Re-enable it once you’ve installed the necessary extensions. Only disable SIP when necessary and understand the potential risks involved.
Installing font awesome pro with bun
After recently switching to bun.sh, I was trying to install Font Awesome Pro. It uses a private registry but their docs have not been updated to support non-npm package managers and bun does not yet support .npmrc files.
You can configure a private registry using an organization scope. First, you must get your auth token from your paid Font Awesome account by going to your account page, scrolling down to the Tokens section, and copying the token.
Copy and paste this string, and replace YOUR_TOKEN_HERE with the token you copied above:
[install.scopes]
"@fortawesome" = { token="YOUR_TOKEN_HERE" , url =
"https://npm.fontawesome.com/"}
Open the terminal and enter these commands:
touch $HOME/.bunfig.toml
nano $HOME/.bunfig.toml
Paste in the config above with your token and then hit CTRL+X to quit, and Y to save when prompted. Now you should be able to run
bun add @fortawesome/fontawesome-pro
Using Laravel Vite with MAMP
As seen in other posts, I use MAMP quite a bit for my web development environment. I know I can run docker, or any of the other platforms out there but they use more memory and resources that I’d prefer to devote to my dev tools.
I started a new Laravel project and wanted to use MAMP but Vite was throwing errors due to the SSL not matching out of the box.
When adding
@vite('resources/js/app.js')
to my blade file, I’d get errors including:
This request has been blocked; the content must be served over HTTPS.
I found articles saying to add –https or –host to my package json command but then I got this error:
net::ERR_SSL_VERSION_OR_CIPHER_MISMATCH
Load MAMP Pro, add your host and generate your SSL certificates. For this example, we’ll use set the host name to my-app.test, and assume you’re storing the SSL keys in the default location.
Open vite.config.js and add the following 2 lines:
import fs from 'fs'; const host = 'my-app.test';
Then add this to defineConfig section:
server: { host, hmr: { host }, https: { key: fs.readFileSync(`/Applications/MAMP/Library/OpenSSL/certs/${host}.key`), cert: fs.readFileSync(`/Applications/MAMP/Library/OpenSSL/certs/${host}.crt`), }, },
You should now be able to run npm run dev and have no issues.
Sample full vite.config.js file for easy reference:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import fs from 'fs'; const host = 'my-app.text'; export default defineConfig({ server: { host, hmr: { host }, https: { key: fs.readFileSync(`/Applications/MAMP/Library/OpenSSL/certs/${host}.key`), cert: fs.readFileSync(`/Applications/MAMP/Library/OpenSSL/certs/${host}.crt`), }, }, plugins: [ laravel([ 'resources/sass/app.scss', 'resources/js/app.js', ]), ], });
How to Get Laravel Debugging to work with PHPStorm and MAMP Pro 5
This has been one of the more aggravating things I’ve had to deal with in setting up software for development. I’ve followed the official documentation from JetBrains, over 30 other blog tutorials, and literally failed in getting any of them to work.
I figured out an easy way to make the setup work so I’m sharing it in case someone else finds it useful and for self-reference since I’ll probably forget how to do this again in 6 months when I start a new project.
MAMP Configuration
- Load MAMP and setup your host. Make note of the host name as you will need it to configure PHPStorm.
- Go to PHP on the left under Languages.
- On the right under Extensions, check Xdebug (Debugger).
PHPStorm Configuration
- Load PHPStorm and load your Laravel project.
- Setup your PHP executable and interpreter as per the official documentation and then resume here.
- On the top right of PHPStorm, select Edit Configurations from the dropdown.
- Click on the Plus Button on the top left of the dialog and then select ‘PHP Web Page’.
- Enter a descriptive name in the textbox. I use the host name from MAMP so it’s easy to identify visually. Click on the 3 dots with next to Server.
- Enter a descriptive name. I use the host name here as well. For the host, omit the http/https and just add the host name from MAMP.
- Click OK
- Now add your breakpoints and click on the Debugger Button on the top right and PHPStorm will load the site into the browser and break when breakpoints are hit.
Happy debugging!
Self-signed SSL certificates not working with MAMP and Chrome
I use MAMP Pro for most of my PHP development and Chrome has annoyingly been blocking the self-signed SSL certificates MAMP generates, saying the certificate is not valid and “Your connection is not private”:
Thankfully, I found an easy solve to fix this. These steps assume you’ve created a host in MAMP. You’ll need to go to the SSL tab of the host you are trying to fix and
- Check the SSL button
- Click the self-signed certificate button.
- Fill in the fields in the dialog modal and click Generate
- You’ll be prompted to save the certificate. Choose whatever location you’d like.
- Click on the circle with the arrow to open the directory where the certificate was saved.
- In the finder window that opens, double click the .crt file (be sure it’s the same file name that’s in the SSL window in case you have multiple).
- In the Add Certificate window, click Add. I testing adding it to login and system and both worked, so add whichever you prefer.
- In the Certificates Window, double click the certificate. It’s easier to filter by name if you have a lot of items.
- In the next modal window, choose Always Trust from the dropdown.
- Close out the next confirmation window, and you’ll be prompted to authenticate with your mac login to save the updates.
Go back to Chrome, and reload the page and the certificate should work now:
How to get website average latency in BASH
I was working on a project today and wanted to be able to get the average latency for an API that I was working on. Performance is a concern because we’re running the API over a VPN, and then SSH tunneling over to another server. I wanted a quick way to do it and wrote a little bash function that will calculate the average for me. I couldn’t find an example on how to do this online so I’m sharing in case anyone else runs into the same issue.
This is tested on Mac only. Add these two functions to your .bashrc and do a shellupdate in terminal to load the latest, or just grab my dotfiles from my github: https://github.com/gregvarghese/dotfiles
curlb(){
curl -s -o /dev/null -w '%{time_starttransfer}\n' "$@"
}
# Usage:
# latencyavg [# of times to run] [URL]
function latencyavg()
{
time=0.00
for (( c=1; c<=$1; c++ ))
do
num1=$(curlb $2 -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: en-US,en;q=0.8,ja;q=0.6' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.86 Safari/537.36' -H 'Connection: keep-alive' --compressed)
echo "$c - $num1"
time=$(echo "$time + $num1" | bc -l)
done
echo "Total Time $time"
echo $(echo $time / $1 | bc -l)
}
Usage example:
latencyavg 20 https://www.godaddy.com
How to fix VMWare Fusion Pro 10 “Cannot find a valid peer process to connect to”
I recently got a new mac and was migrating a VMWare Windows Virtual Machine from my other computer. When starting the virtual machine, I received a random message from VMWare Fusion saying “Cannot find a valid peer process to connect to.”
The fix was rather simple as it was just Apple blocking VMWare from running. To fix it, follow these steps:
- Open System Preferences by searching in Spotlight or clicking the gear icon in the dock.
- On the top row there is an icon for Security and Privacy – Click that icon
- Near the bottom of the screen that appears the following statement
“System software from developer “VMWare, Inc.” was blocked from loading” - Click Allow
List of my must-have Alfred Workflows
Use a mac? You’ll want to grab Alfred App. I’m finding it an invaluable replacement for spotlight and the workflows allow me to supercharge my workflows. It’s so useful that I’ve purchased the Powerpack lifetime license.
In addition to the standard features, here are a list of the most useful workflows for dev/tech:
Kill process – by Nathan Greenstein (@ngreenstein)
I use it as an activity monitor for CPU usage, and from there I can easily force quit any process if needed. It’s easier to see all processes on the Alfred UI instead of opening Activity Monitor on your mac. There’s also the workflow Kill Application – by Sebastian Hallum Clarke (and also on his site you can find other cool workflows).
Timer – by Daniel Bader
I use this one a lot. It’s super simple and by writing “Timer” and the number of minutes, you can easily set a reminder. It’s great for anyone using the Pomodoro technique or even if you leave something on the stove and want to go back to work.
Copy SSH Public Key – By oldcai
This one saves me time when I need to deploy my SSH key on a new server. Type ‘pk [ssh key file name]’ and it’ll copy the ssh key to the clipboard.
Incognito – by Nedwood
I find myself using this when I need to test a page and bypass the cache. Type ‘incog [url]’ and it’ll launch a new chrome window in incognito mode.
Find Folder by Samvlu
Finds a folder by name. I find this is faster than spotlight in just about every search.
Smart Folders by Deanishe
List all the Smart Folders/Saved Searches (same thing) on your system and drill down into their contents. Works in much the same way as Alfred’s File Filter, but Smart Folders are also available outside Alfred and are a bit more flexible.
For example, you can configure a Smart Folder to show all video/audio/image files without having to specify each different filetype individually. If you already use Smart Folders, this workflow can save you the work of re-implementing them as File Filters.
What’s more, you can exclude specific filetypes with a Smart Folder, which Alfred cannot do.
Advanced Google Maps Search by stuartcryan
This workflow gives you some quick and dirty shortcuts into Google Maps:
Commands:
To Configure:
mapsethome <home address including street number, name, postcode> (i.e. what you would type into Google Maps)
mapsetwork <work address including street number, name, postcode> (i.e. what you would type into Google Maps)
Commands for Use:
maps <query> – Search Google maps for an address
dir <query> to <query> to <query> etc (seperate multiple addresses with ” to ” minus the quotes, and you will get a multiple location search)
dirfw Show directions from Work to address
dirfh Show directions from Home to address
dirtw <query> Show directions from query to Work address
dirth <query> Show directions from query to Home address
trafficw – Show traffic from Home to Work
traffich – Show traffic from Work to Home
StackOverflow Search by deanishe
If you use stackoverflow as much as I do, this is a must-have.
Date Calculator
I find myself needing to calculate differences between dates in my personal life a lot lately. This workflow saves me a lot of time to do that. Want to know how far Christmas is away in days? ‘dcalc 12-25-16 – now d’ returns the number of days (assuming you’re using the US short format like I am).
Wifi Control by miroman
All my Macbooks periodically have issues with wifi. I’ve never been able to figure out what’s causing it but I use Wifi Control to restart the wifi which allows me to connect successfully.
Bugnot by vitor
If you use bugmenot at all, this is a useful extension to get logins without loading a new tab. Type ‘bn domain.com’ and you’ll get a list of matching passwords to use.