No more UUID/GUIDs

Submitted by Donny5300 - 6 months ago

This example provides a quick and simple method to generate a hash for a model without saving a UUID/GUID to the database.

<?php

    /**
     * Attach a hash to the user model. This way we dont need a UUID/GUID. Keep
     * in mind that the HASH will change every time when you instantiate the
     * User model
     * 
     * Class User
     */
    class User extends Model
    {
        protected $appends = [ 'hash' ];

        /**
         * @return string
         */
        public function getHashAttribute()
        {
            return encrypt( $this->id );
        }
    }

?>

<?php
    # Route
    Route::get( 'user/{user_hash}/show', [
        'as'   => 'user.show',
        'uses' => 'UserController@show'
    ] );

    # Model Binding
    /**
     * @throws \Illuminate\Contracts\Encryption\DecryptException
     */
    app( 'router' )->bind( 'user_hash', function ( $hash ) {
        return app( User::class )->findOrFail( decrypt( $hash ) );
    } );
?>

<!-- Create a link -->
<a href="{{route('user.show', [$user->hash])}}">Edit</a>

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks