T
T
Tikhon Ermakov2020-08-05 05:49:49
Laravel
Tikhon Ermakov, 2020-08-05 05:49:49

How to extend a project on Laravel?

Good afternoon!

I ask you to look at the following code and criticize :)

We have both authorized and unauthorized users in the application.
For the most part, we'll be working with the contents table and a bit of user subscriptions.
Content can be either absolutely free (available) or paid. To be more precise, in order to get it, the user must have a subscription, and of course, when he requests it, he must be authorized.

I'm using React on the frontend, and came up with locked .

locked - is responsible for whether we will display to the user that this content is available or not. We display it simply - in the form of a castle.

Content Model

protected $hidden = ['secret'];

protected $appends = ['locked'];

public function getLockedAttribute()
{
    // Платный ли контент.
    if ($this->attributes['is_paid'] == true) {
      // Проверяем  авторизован ли пользователь или на наличие подписки
      if (! Auth::check() || Carbon::parse( Auth::user()->membership_ends_at ) < Carbon::now() {
          return $this->attributes['locked'] = true;
      }
    }

    // По умолчанию контент доступный.
    return $this->attributes['locked'] = false;
}


Also, by default, we are in no rush to send our secret .
The following code is in the controller.

foreach ($rootModel->contents as $content) {
   if (! $content->locked) {
       // Делаем видимым наш secret.
       $content->makeVisible('secret');
    }
}


I want to expand my project. I really don't like what's going on in getLockedAttribute() .

I want to create a manager who is responsible for subscriptions. Some class that will return us a value in Bool, whether the user has permissions (subscription) or not. Yes, and other things. What is now, for me, is dirty code and not DRY at all .

I did not understand or find anything in the documentation, rather the second option. What should I study and how do they do it?

Please send me how you code, what would you change and how to extend the backend application ?

Regarding the fact that we store the value of the subscription expiration in the user table ... In my opinion, everything is fine, since these are temporary measures.

Thanks to!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-08-05
@the_goldmayer

Create a policy , attach it to the resource controller, write in the view method of the policy

return !$post->isPaid or optional($user)->hasSubscription;

Create an api resource for posts, write a policy check, rewrite the hasSubscription method, remove it from the appends model Gate::allows('view', $this)
return $this->membership_ends_at >= now();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question