nWidart / laravel-modules

Module Management In Laravel
https://docs.laravelmodules.com
MIT License
5.48k stars 949 forks source link

Elequent relationship #1912

Closed thesiamak01 closed 19 hours ago

thesiamak01 commented 1 month ago

Hi there,

I've developed a new module called "ticket". I've successfully added a hasMany relationship to the User model to associate users with multiple tickets.

public function tickets() { return $this->hasMany(Ticket::class); }

My goal is to automate this process. I'd like this relationship to be defined automatically when the module is installed, rather than manually adding it to the User model.

Is there a way to achieve this dynamic registration of the relationship?

Thanks.

abdokouta commented 1 month ago

@thesiamak01, I think there is a simple approach to achieve that by extending the User model in the Ticket module and binding it to the service provider

pravnkay commented 6 days ago

@abdokouta Can you kindly give an example of what you mean by binding it to the service provider ?

dcblogdev commented 19 hours ago

The following should work, this is untested.

Extend the User Model in the Ticket Module:

In your Ticket module, create an extended version of the User model where you define the tickets() relationship. You don’t need to modify the core User model; instead, Laravel allows you to extend it dynamically via service providers.

Create a User Extension in the Module:

Inside your Ticket module, create a class that extends the User model and adds the tickets() relationship. For example:

// Modules/Ticket/Extensions/UserExtension.php
namespace Modules\Ticket\Extensions;

use App\Models\User;

class UserExtension extends User
{
    public function tickets()
    {
        return $this->hasMany(\Modules\Ticket\Models\Ticket::class);
    }
}

Bind the Extended User Model in the Module’s Service Provider:

Now, in your Ticket module’s service provider, you can use the extend() method to bind the extended version of the User model.

// Modules/Ticket/Providers/TicketServiceProvider.php
namespace Modules\Ticket\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\User;
use Modules\Ticket\Extensions\UserExtension;

class TicketServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Bind the extended User model
        $this->extendUserModel();
    }

    protected function extendUserModel()
    {
        User::extend(function($model) {
            // Attach the tickets relationship dynamically
            $model->morphMany('tickets', \Modules\Ticket\Models\Ticket::class);
        });
    }
}