PHP code example of ryancco / laravel-uuid-models

1. Go to this page and download the library: Download ryancco/laravel-uuid-models library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ryancco / laravel-uuid-models example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Ryancco\HasUuidRouteKey\HasUuidRouteKey;

class Post extends Model
{
    use HasUuidRouteKey;
}



use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddUuidColumnToPostsTable extends Migration
{
    public function up(): void
    {
        Schema::table('posts', static function (Blueprint $table) {
            $table->uuid('uuid');
        });
    }
}


// Route registration works exactly as it had with models routed by the "id" attribute

// "binded" routes
Route::get('posts/{post}', 'PostController@show');

// resourceful routes
Route::resource('posts', 'PostController');

// ...



namespace Tests\Feature;

use App\Models\Post;
use Tests\TestCase;

class PostsControllerTest extends TestCase
{
    public function testAdminsHavePermissionToViewPrivatePosts(): void
    {
        $post = factory(Post::class)->state('private')->create();

        $this->get(route('posts.view', $post))->assertOk();
        // route('posts.view', $post->uuid) - localhost/posts/94205252-7c44-4e5b-ad75-682ac81fea84
    }
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Ryancco\HasUuidRouteKey\HasUuidRouteKey;

class Post extends Model
{
    use HasUuidRouteKey;

    public function getRouteKeyName() : string
    {
        return 'something-else';
    }
}



$post = new App\Models\Post();
$post->generateUuidRouteKey();