Php Laravel Snippets Enter a brief summary for this post

PHP Laravel Snippets

I will share with you PHP code snippets on this blog post in no particular order. As and when I add them really.

Reverse Laravel's Str::slug()

The quick, and dirty way to reversing the slug (having used Laravel's helper function) is simply to do a string replace, however the kinder way of doing the reserve is with the following. This is for completeness ensuring there are no trailing spaces or erroneous characters.

use Illuminate\Support\Str;
// ... etc ...
$slug=Str::of($slug)->replace('-', ' ')->title();

Using Laravel's Observers with DB Commits

There are many use cases when you need to perform an operation but only after a database transactional commit. If the commit fails for whatever reason, then nothing goes ahead. I'll demonstrate two use cases to you. The first is you have a database table for holding filename information for photos. You want to delete a record but you must also include the physical file(s) in the deletion.

use App\Models\Photo;

use Log;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class PhotoObserver
{
    public function created(Photo $photo) {}
    public function updated(Photo $photo) {}
    public function restored(Photo $photo) {}

    public function deleted(Photo $photo)
    {
        /**
         * @note    must register observer with the event service provider, in the ::boot(); 
         *          method, for this to work properly:
         * 
         *          Photo::observe(PhotoObserver::class);
         */
        
        if(Storage::disk('s3')->exists('original/'.$photo->filename))
        {
            Storage::disk('s3')->delete('original/'.$photo->filename);
        }

        if(Storage::disk('s3')->exists('dev/'.$photo->filename))
        {
            Storage::disk('s3')->delete('dev/'.$photo->filename);
        }

        if(Storage::disk('s3')->exists('dev/thumb/'.$photo->filename))
        {
            Storage::disk('s3')->delete('dev/thumb/'.$photo->filename);
        }
    }

As noted in the comments you must register the Observer for it to work. Now all those files on the Amazon S3 bucket will be vanquished once the corresponding database record has been deleted. The second use case is you must send out a confirmation email for a new newsletter subscriber. The Observer in question looks like this one below.

class SubscriberObserver
{
    protected function getPostService() : PostService
    {
        return new PostService(new PostRepository());
    }

    public function created(Subscriber $subscriber) 
    {
        SubscriberConfirmationEmailJob::dispatch(
            $subscriber
          , $this->getPostService()->getRepository()->findRandom(12)
        )->delay(now()->addSeconds(10));
    } // ... etc ...

Isolate (extract) IDs from an Eloquent Collection

I had a situation where I needed to delete a number of rows using a whereIn condition. To do that I had to get those IDs out of a collection. Returning an array from the collection resulted in each index being associative, which wasn't ideal.

The obvious solution was to use the map function with a Closure:

$ids=Category::select('id')->get()->map(function($k, $v) 
    {
        return $k['id'];
    });

Category::whereIn('id', $ids)->delete();

Copy and paste an existing image under a new file name

Imagine a new user has a profile image and you leave them with a default for the time being. The following snippet will easily copy the default profile image and rename it all in one for you.

use Illuminate\Support\Facades\Storage;</code>
<code>Storage::disk('public')->put('/images/'.$user->username.'-profile.jpg',
                Storage::disk('public')->get('/images/default-profile.jpg')
            );

Where $user is an instance of a User model obviously.