Search code examples
laravelrelationshipuuid

Laravel Relationship Find UUID


I have make a Trait for UUID. I use a lot of relationschip inside my code. On a relationship you can do find() and findOrFail() but i have write a code for findU() and findUOrFail() but i can't use it inside a relationship. How can i fix it?

Trait:

<?php

namespace App\Modules\Base\Traits;

use Ramsey\Uuid\Uuid;

/**
 * Trait Uuids
 *
 * @package Modules\Core\Traits
 */
trait Uuids
{
    /**
     * Boot function from laravel.
     */
    public static function bootUuids ()
    {
        static::creating(function ($model) {
            $model->uuid = Uuid::uuid4()->toString();
        });
    }

    /**
     * @param $uuid
     *
     * @return mixed
     */
    public static function findU ($uuid)
    {
        return static::where('uuid', '=', $uuid)->first();
    }

    /**
     * @param $uuid
     *
     * @return mixed
     */
    public static function findUOrFail($uuid)
    {
        $post = static::where('uuid', '=', $uuid)->first();

        if( is_null($post) ) {
            return abort(404);
        } else {
            return $post;
        }
    }

}

Controller:

/**
     * Show
     */
    public function show(Request $request, $uuid)
    {
        return responder()->success($request->user()->projects()->findUOrFail($uuid))->respond();
    }

Error: Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany::findUOrFail()


Solution

  • Assuming you don't need id since you're using uuid

    In your migration file you need:

    $table->uuid('uuid');
    $table->primary('uuid');
    

    In your model:

    use Uuids;
    protected $primaryKey = 'uuid';
    public $incrementing = false;
    

    Or much easier

    In your migration file:

    $table->uuid('id');
    $table->primary('id');
    

    In your model:

    use Uuids;
    public $incrementing = false;
    

    You don't need to override findOrFail or find