Skip to main content

Attach unique in BelongsToMany Laravel/Eloquent

As you probably know, you can use the attach() method to relate two models within a BelongsToMany relationship. The only problem with attach() is that it doesn’t check to see if the relationship already exists. So, essentially, you could attach the same model more than once to a relationship, which isn’t ideal.

For instance, you have pizzas and ingredients.

You could always do something like this:

$relationship = $pizza->ingredients()->where('ingredient_id', $ingredient->id)->get();
if(!$relationship)
{
$pizza->ingredients()->attach($ingredient);
}

Or, you could use this method, which checks if the relationship exists and it doesn’t double up:

$pizza->ingredients()->syncWithoutDetaching($ingredient);

What this will do is sync the ingredient with the pizza (like the sync() method), however, if the relationship already exists, it won’t do anything. The relationship will stay, and nothing else will detach.

Unique email validation in Laravel when re-saving model

When you validate an email in Laravel, you have the ability to specify whether you want a specific model to be excluded. The reason why you would exclude a model is for example, if you have a user account and the user needs to update their first name, but their email stays the same. Typically, Laravel would re-save the whole form and also validate the email, but because that user is already using the email, it will spit back a “unique” validation error mentioning the email already exists in the system (even though it is still being used by said user.

Read More

Download from Google Drive direct from cPanel server

I store cPanel backups on Google Drive and needed to restore a backup of a website which was 9GB.

Instead of downloading the file to my computer and re-uploading it to the server (which could take a considerable amount of time), I wanted to download the file straight from Google Drive to the server, this will download faster due to the connection of the server.

Unfortunately, a standard WGET does not work.

To do this, I went into Terminal for my cPanel server and downloaded pip:

Read More

Batch script to update WooCommerce product titles

I had a client who had named all of his 600+ products to uppercase and Google Shopping was not allowing the products to be indexed because of this.
To automatically rename the Woocommerce Product titles, I ran this script:

This will loop through each product and rename the titles to capitalised using php UCWORDS()

For example: MY PRODUCT will be renamed to My Product.

Read More

Add featured image to admin table in WordPress for custom post type

On a project I’m doing, I created a custom post type for a catalogue and want the featured image to display on the admin table.

My custom post type is called “product” and I want to limit the feature to only the “product” custom post type. Here’s how I did it.

I added this into functions.php

Read More