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.
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', ]), ], });
Add GTM to Gatsby using Helmet
One of my devs needed to add Google Tag Manager (GTM) to an older Gatsby project we built and he was running into issues implementing the GTM code provided by Google since the react-google-tag-manager package required a newer version of Gatsby and its dependencies.
The issue turned out to be that the strings needed to be escaped for Helmet/React to process it correctly. If you’re using an older version of Gatsby, the snippet below should help you add GTM and call your events as needed. Just add it to your main template file.
const googleAnalyticsId = 'your-google-id-here'
<Helmet>
<script async src={`https://www.googletagmanager.com/gtag/js?id=${googleAnalyticsId}`}></script>
<script>
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', "${googleAnalyticsId}");
`}
</script>
</Helmet>
How to Setup CI/CD of Jigsaw Site to Digital Ocean Droplet Using Bitbucket Pipelines
I created a new personal resume site and decided I wanted to build a static site since it wouldn’t be frequently updated. I evaluated Nuxt, Gatsby, and a few others but settled on Jigsaw, a static site generator based on Laravel. I had never used it before and figured this would be a good learning experience while building something I needed. I was pleasantly surprised by how easy it is to use and setup, so kudos to the Tighten team for putting together such an elegant solution.
I wanted to get a CI/CD pipeline configured to handle the site’s deployment but couldn’t find any working tutorials, so I’m sharing my solution in case it helps others. I’m using Bitbucket for this since it’s a personal private repo, so I’m using Bitbucket Pipelines.
Instructions
After you enable pipelines for your project, you’ll need to configure a Pipelines Repository Variable in your project. Go to the settings tab in your repo, and then select Repository variables:
Add 3 variables:
- USER_NAME – The SSH user name you want Bitbucket to use to connect to your server.
- PRODUCTION_HOST – Your domain that Bitbucket should connect to
- FOLDER – Folder Path where the site should be deployed to
Generate an SSH key (or use your own) and add it to your server under the SSH Keys tab in Pipelines:
I generated a new key and then added it to ~/.ssh/authorized_keys for the account.
Add this YAML snippet to your bitbucket-pipelines.yml in your root. This will use PHP 7.4, install rsync, node + npm, composer, and build the production version of the site to deploy to the specified folder.
The -aVP switch for rsync is to give me verbose progress feedback so I can see what’s happening. If you don’t need the detail, switch it to -a.
image: php:7.4-fpm
pipelines:
branches:
master:
- step:
name: Jigsaw Build
script:
- apt-get update && apt-get install -y unzip
- apt-get install rsync openssh-client nodejs npm -y
- curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
- composer install
- npm install
- npm run production
- rsync -avP build_production/ $USER_NAME@$PRODUCTION_HOST:$FOLDER --exclude=bitbucket-pipelines.yml --chown=www-data:www-data
I received a few errors when rsync ran. In case you run into them as well, here’s the list and fixes. The first was:
rsync: failed to set times on "$FOLDER": Operation not permitted (1)
I added --no-t
to resolve that and then got a new error:
rsync: failed to set permissions on "$FOLDER": Operation not permitted (1)
which was fixed with adding the switch --no-perms
. My final rsync command became:
rsync -avP --no-t --no-perms build_production/ $USER_NAME@$PRODUCTION_HOST:$FOLDER --exclude=bitbucket-pipelines.yml --chown=www-data:www-data
How to use Backblaze B2 with Laravel
I am working on a Laravel project and decided to use a Backblaze bucket as it’s cheaper for storage when compared to AWS S3. I couldn’t find a tutorial on how to get it working from scratch and I tested a bunch of Laravel B2 libraries that didn’t end up working. The good news is that you don’t need a special B2 plugin and instead can use the S3 package recommended by the Laravel docs.
If you haven’t added the flysystem-aws-s3 package, add it to your project using composer:
composer require league/flysystem-aws-s3-v3
Login to your B2 account and create your bucket with your required settings. Once created, you’ll want to create a new application key with the permissions you need for your app. You should get a confirmation once it’s generated:
Open your .env file and locate the settings for AWS. You’ll need to add one key that’s not there by default:
AWS_ENDPOINT=
Match the settings in your .env from the application key to the values below.
AWS_ACCESS_KEY_ID=keyID
AWS_SECRET_ACCESS_KEY=applicationKey
AWS_DEFAULT_REGION=us-west-000
AWS_BUCKET=bucket-name
AWS_ENDPOINT=S3 Endpoint
Now you should be able to call the Laravel storage system like normal:
\Storage::disk('s3')->put('test.txt', 'test');
How to Clear Archive & Read-only flags on Files in Windows in Bulk
I ran into an issue where I had to move files from one system to another and was running into issues because files had been set as read-only, had the archive flag set, or both. It was causing the system to skip files which wasn’t acceptable. Normally you could just use Windows to clear it in bulk, but that could potentially mess up file permissions. I needed a way to automatically just clear all flags but respect permissions.
I did some searching and didn’t find a utility that would do the job and most of the solutions I found required Powershell which wasn’t available on the system I was on. I ended up writing a quick console application in C# to do the trick. I’ve made it free and open sourced it in case anyone wants to use it.
If you need just the app, you can find the release build here with instructions. The app also prompts for input to make things a bit easier to use. There’s no install, no tracking or metrics, or anything else related to privacy concerns in this app. It’s a simple throwaway utility to get the job done and move on.
https://github.com/gregvarghese/clearflags/releases/tag/1.0.0
If you want to see the source code, that is available here:
https://github.com/gregvarghese/clearflags/
Please note that I did this in about 10 minutes for my own use so error handling is pretty much non-existent. I mention this because I did run into one issue where Windows was somehow seeing a folder with files in it as a file and it couldn’t be deleted or renamed and the utility couldn’t get past it until it was resolved. I didn’t spend much time debugging and just used my Mac to rename the folder and Windows was able to recognize it after the change, so the utility was able to continue processing.
How to Generate a Page for Each Day of Month in Microsoft Word using VBA
I briefly joined my wife at her practice to help her grow the business and figure out how to make things more efficient. One of the things I learned is that my wife created a sign-in sheet for the office in Microsoft Word. Every week she would open the file and manually enter the date for each day of the week and then print out the documents. I took over the responsibility for a month and it annoyed me due to how inefficient the process was and I decided to automate the entire thing. I couldn’t find a solution to the problem online so I had to roll my own and am sharing the code in case someone else can benefit from it.
Important Details
The script will calculate the first day and last day of the month and then do a loop to append the date in the “Day, Month day, Year” format (i.e. Thursday July 17, 2019) to a text field.
There are a few important steps involved to get the script working as is:
- Create a Word doc with the first page that you want to duplicate.
- Add a text field from the developer tab. To copy and paste the code below as-is, you’ll need to name it txtDate. This is where the date will be added. If you want a different field name, change the name at line 26 and 83. You can also change the date formats to suit your needs here as well.
- Add a second blank page to the document. I was running into issues where the paste was appearing partially on the first. The blank page resolved this and I added code to remove the original page as well as the blank one from the beginning.
How to Use
Open up Word, then open up VBA, and copy and paste this snippet into a module. When you run the function, it’ll create a copy for every day of the month. I also created a function to start at a specific date in case you run it in the middle of the month.
Sub CreateSigninsForMonth()
Dim N As Integer
Dim sCurrentMonth, sCurrentYear As String
Dim sNewDate As String
N = 1
Count = Day(GetLastDayOfMonth)
For CopyNumber = 1 To Count
With Selection
.GoTo wdGoToPage, wdGoToAbsolute, 1
.Bookmarks("\Page").Range.Copy
.Paste
End With
With ActiveSheet
sCurrentMonth = Format(Date, "mmmm")
sCurrentYear = Format(Date, "yyyy")
sNewDate = (CopyNumber & " " & sCurrentMonth & " " & sCurrentYear)
ActiveDocument.FormFields("txtDate").Result = Format(sNewDate, "DDDD MMMM dd, YYYY")
End With
N = N + 1
Next CopyNumber
'Delete template + blank page
For i = 1 To 2
With ActiveDocument
strt = .GoTo(wdGoToPage, wdGoToLast).Start
Set r = .Range(strt - 1, .Range.End)
r.Delete
End With
Next
End Sub
Sub CreateSigninsForMonthStartingDate()
Dim Count As Integer
Dim N As Integer
Dim sCurrentMonth, sCurrentYear As String
Dim sNewDate, sEndDay As String
N = 1
Count = 0
iStartDay = InputBox("Which day do you want to start on?", "Starting Day", "1")
Count = InputBox("Which day do you want to end on?", "Ending Day", Day(GetLastDayOfMonth))
Do While Count > Day(GetLastDayOfMonth)
sEndDay = InputBox("Which day do you want to end on?", "Ending Day", Day(GetLastDayOfMonth))
If iStartDay = vbNullString Or sEndDay = vbNullString Then
MsgBox "You clicked cancel.", vbOKOnly, "Try again later!"
Exit Sub
End If
If IsNumeric(CInt(sEndDay)) Then
Count = CInt(sEndDay)
End If
Loop
For CopyNumber = iStartDay To Count
With Selection
.GoTo wdGoToPage, wdGoToAbsolute, 1
.Bookmarks("\Page").Range.Copy
.Paste
End With
With ActiveSheet
sCurrentMonth = Format(Date, "mmmm")
sCurrentYear = Format(Date, "yyyy")
sNewDate = (CopyNumber & " " & sCurrentMonth & " " & sCurrentYear)
ActiveDocument.FormFields("txtDate").Result = Format(sNewDate, "DDDD MMMM dd, YYYY")
End With
N = N + 1
Next CopyNumber
'Delete template + blank page
For i = 1 To 2
With ActiveDocument
strt = .GoTo(wdGoToPage, wdGoToLast).Start
Set r = .Range(strt - 1, .Range.End)
r.Delete
End With
Next
End Sub
Function GetFirstDayOfMonth(Optional dtmDate As Date = 0) As Date
' Return the first day in the specified month.
If dtmDate = 0 Then
' Use the current date if none was specified
dtmDate = Date
End If
GetFirstDayOfMonth = DateSerial(Year(dtmDate), Month(dtmDate), 1)
End Function
Function GetLastDayOfMonth(Optional dtmDate As Date = 0) As Date
' Return the last day in the specified month.
If dtmDate = 0 Then
' Use the current date if none was specified
dtmDate = Date
End If
GetLastDayOfMonth = DateSerial(Year(dtmDate), Month(dtmDate) + 1, 0)
End Function
How to Automate Sending Emails through Outlook interop using C#
I was tasked with a tricky issue in sending emails. Due to security concerns, the client’s IT team was not willing to share SMTP information for their mail settings and was only willing to set up an account in Outlook directly on a dedicated machine without sharing the password with us to send the emails. The client’s ask was to send emails through Outlook without letting users see the emails or Outlook itself.
Installing Office Interop for Outlook
Sending emails through Outlook can be done using Microsoft.Office.Interop.Outlook but the documentation is really lacking. If you need to do the same, I hope this will save you the hours of time it took me to figure out what ends up not being complex code.
Create a new desktop application project in Visual Studio. Install the Microsoft Office Interop for Outlook. I used the NuGet package manager to install it since it wasn’t present on my system:
Install-Package Microsoft.Office.Interop.Outlook
Automating E-mails using C#
I created a static class to send the email through Outlook. Note that my error handling code was replaced with Debug.Writeline. Remember to modify it to handle errors or implement logging so it doesn’t fail silently.
Email.cs:
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Outlook;
using Exception = System.Exception;
namespace Email.classes
{
public class Email
{
public static void SendWithEmbeddedImages(string to, string subject, string htmlMessage)
{
var missing = Type.Missing;
Application oOutlook = null;
NameSpace oNS = null;
Folder oCtFolder = null;
Items oCts = null;
MailItem msg = null;
var sHeaderPath = Path.Combine(Environment.CurrentDirectory, "emails", "header.jpg");
var sLogoPath = Path.Combine(Environment.CurrentDirectory, "emails", "logo.jpg");
try
{
// Create an Outlook application.
oOutlook = new Application();
// Get the namespace.
oNS = oOutlook.GetNamespace("MAPI");
//Assumes MAPI profile name is Outlook
oNS.Logon("Outlook", missing, false, true);
msg = (MailItem) oOutlook.CreateItem(OlItemType.olMailItem);
var attachHeader = msg.Attachments.Add(sHeaderPath, OlAttachmentType.olEmbeddeditem);
var attachLogo = msg.Attachments.Add(sLogoPath, OlAttachmentType.olEmbeddeditem);
attachLogo.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", "logo");
attachHeader.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E",
"header");
msg.Subject = subject;
msg.To = to;
msg.BodyFormat = OlBodyFormat.olFormatHTML;
msg.HTMLBody = htmlMessage;
//Show email
msg.Display();
//Send email
//((Outlook._MailItem)msg).Send();
oNS.Logoff();
}
catch (Exception ex)
{
Debug.WriteLine("Automate Outlook throws the error: {0}", ex.Message);
}
finally
{
// Manually clean up the explicit unmanaged Outlook COM resources by
// calling Marshal.FinalReleaseComObject on all accessor objects.
// See http://support.microsoft.com/kb/317109.
if (msg != null)
{
Marshal.FinalReleaseComObject(msg);
msg = null;
}
if (oCts != null)
{
Marshal.FinalReleaseComObject(oCts);
oCts = null;
}
if (oCtFolder != null)
{
Marshal.FinalReleaseComObject(oCtFolder);
oCtFolder = null;
}
if (oNS != null)
{
Marshal.FinalReleaseComObject(oNS);
oNS = null;
}
if (oOutlook != null)
{
Marshal.FinalReleaseComObject(oOutlook);
oOutlook = null;
}
}
}
}
}
Example on how to call the class:
var sEmailPath = Path.Combine(Environment.CurrentDirectory, "emails", "single.html");
var htmlMessage = "";
if (File.Exists(sEmailPath))
{
//Load HTML from file
htmlMessage = File.ReadAllText(sEmailPath);
}
Email.SendWithEmbeddedImages("toaddress@test.com", "Outlook Automation Test", htmlMessage);
email.html:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
</head>
<body>
<table width="600" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td><img src="cid:header"></td>
</tr>
<tr>
<td>
Hello world!
</td>
</tr>
<tr>
<td><img src="cid:logo"></td>
</tr>
</table>
</body>
</html>
Important Notes and Gotchas
- CIDs need to be unique. I’ve seen them on all other posts with the format “file.extension@{random #}” but keeping it simple like in the code above worked for me with no issues with Outlook 2016. I did not test on older versions of Outlook to confirm as I no longer have access to them.
- Outlook ignores font rules in the HTML/CSS you code in the email and defaults to Times New Roman. I know Outlook uses the Word renderer but I have no idea why and the only solution I found was to update the default font in Microsoft Word. Yes, to change the font in Outlook, you’ll need to update the default font in Word. Here’s how to set it:
- Open Word
Go to Options -> Advanced -> Web Options
Change the default font in the Fonts tab
- Open Word
- Outlook only supports a subset of HTML so don’t forget to test and verify everything as most CSS formatting won’t work in Outlook.
How to Extract Text from image using Laravel and Amazon Rekognition API
I’m currently working on a project that requires extracting text from images of variable quality. I’m doing quick prototypes using PHP and Laravel, but I’ve found the documentation for accomplishing this a bit lacking. After working on it for a bit, I figured out a really simple solution and am sharing in case it helps anyone else.
This sample will send the image to the API as a blob instead of using a URL. I had tried Base64 encoding it without any luck. I discovered that using Imagick was the easiest way to make this work so the sample relies on that.
Fire up terminal and add a requirement for aws/aws-sdk-php:
composer require aws/aws-sdk-php
Add keys for your AWS access keys and region to your .ENV file:
AWS_REGION=YOUR_REGION
AWS_SECRET_ACCESS_KEY=ENTER_YOUR_KEY
AWS_ACCESS_KEY_ID=ENTER_YOUR_KEY
Create a controller, add the snippet below, and create a route to the controller. Check the URL and you should have a dump showing the array returned from AWS with all the text, bounding boxes, and information.
//Build config array for AWS variables
$config = array(
'region' => env('AWS_REGION'),
'version' => 'latest',
'credentials' => array(
'key' => env('AWS_KEY'),
'secret' => env('AWS_SECRET')
)
);
//Replace with path to image or uploaded image.
$path = '{path to image.jpg}';
$image = new Imagick($path);
$imdata = $image->getImageBlob();
$client = new RekognitionClient($config);
$result = $client->detectText([
'Image' => ['Bytes' => $imdata],
]);
//Dump Result
dd($result);
How to Execute a Stored Procedure in Laravel 5.6
I’ve been stumped on this and tried everything I can think of but I can’t get Laravel to execute a working mysql query to reorder an ordering column when deleting a row.
Here’s a sample simplified query, which works directly in mysql:
SET @number = 3; UPDATE images SET order = (@number := @number + 1) WHERE id >2 AND project_id = 10
Laravel code that doesn’t update the database but throws no errors:
$sql = 'SET @number = 3; UPDATE images SET order = (@number := @number + 1) WHERE id >2 AND project_id = 10';
DB::raw($sql);
Other things I’ve tried which throw errors including saying there’s an error in the query:
DB::unprepared($sql);
DB::statement(DB::raw($sql);
DB::statement($sql);
DB::update($sql);
DB::select($sql);
I’ve also tried splitting it the statements with no luck:
DB::statement("SET @number = 3;");
$sql = 'UPDATE images SET order = (@number := @number + 1) WHERE id >2016 AND project_id = 10';
$update = DB::update($sql);
I tried a few other things which I didn’t log in Git but I had no luck getting any of it to work. I asked for help on the forums and people told me to use Laravel’s Eloquent model to update rows one by one which is pretty inefficient. You get extra trips over the network (especially important when the code is not on the same server as the database server since you can get dropped calls), extra connections to the server, the extra overhead of processing the query on the server and in the database, etc instead of just having mysql make the update.
The recommended solution may not seem like a big deal but I’ve run into issues where client connections have been dropped mid-update and left a table partially renumbered.
As a last resort and workaround, I opted to use a stored procedure to accomplish my goal. That presented its own can of worms as searching for examples on how to execute stored procedures in Laravel 5.x was also not easy. There’s nothing in the documentation and all the examples I found didn’t work.
Here’s what worked for me with Laravel 5.6, with mySQL 5.6.38:
DB::statement('call spRenumberComments(?, ?)', [$id, $projectid);