open-southeners/laravel-model-permalink

Add permalinks to your application's Eloquent models

1.1.0 2023-10-31 10:23 UTC

This package is auto-updated.

Last update: 2024-04-30 00:40:07 UTC


README

Add permalinks to your application's Eloquent models

Getting started

composer require open-southeners/laravel-model-permalink

Usage

First run the command to publish the config and required migrations files:

php artisan vendor:publish --provider="OpenSoutheners\\LaravelModelPermalink\\ServiceProvider"

Then run new migrations:

php artisan migrate

And add the PermalinkAccess interface, HasPermalinks trait and getPermalink method to the models you want to have permalinks:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use OpenSoutheners\LaravelModelPermalink\HasPermalinks;
use OpenSoutheners\LaravelModelPermalink\PermalinkAccess;

class Post extends Model implements PermalinkAccess
{
    use HasPermalinks;

    /**
     * Get permanent link for this model instance.
     */
    public function getPermalink(): string
    {
        // Here is where you return the route that all posts permalinks should use...
        return route('posts.show', $this);
    }
}

Now to generate permalinks to this Post or any configured model you can call the following anywhere in your application's code:

<?php

use App\Models\Post;
use OpenSoutheners\LaravelModelPermalink\GeneratePermalink;

$post = Post::find(1);

GeneratePermalink::for($post);

// or getting directly the route from returned ModelPermalink object

GeneratePermalink::for($post)->getModelPermalink();

Route permissions

The only permalinks route that this package creates is by default accessible to anyone.

This can be configured within gate using the following code on your AppServiceProvider or any other service provider's boot method:

use Illuminate\Database\Eloquent\Model;
use App\Models\User;
use Illuminate\Support\Facades\Gate;

Gate::define('viewModelPermalink', function (?User $user, Model $model) {
    // you can replace this with whatever you like...
    return match (get_class($model)) {
        \App\Models\Post::class => $model->author->is($user),
        \App\Models\User::class => $model->is($user),
        default => false,
    };
});

Partners

skore logo

License

This package is open-sourced software licensed under the MIT license.