Skip to content

Keepable model

Anton Komarev edited this page Mar 19, 2019 · 3 revisions

Setup a keepable model

Keep functionality required when you are trying to attach related models before parent one isn't persisted in application.

Issue:

  1. User press Create Post button.
  2. Create post form has image uploader.
  3. On image uploading user can't attach image to post before post entity wouldn't been stored in database.

Solution:

  1. Add HasKeptFlag trait to model (and add boolean is_kept column to model's database table).
  2. Create empty model on form loading (it will has is_kept = 0 by default).
  3. Feel free to add any relations to the model.
  4. Model will be marked as required to be kept as soon as model will be saved\updated for the first time after creation.

Known limitations:

  • Using this methodology you wouldn't have create form, only edit will be available.
  • Not all the models allows to have empty attributes on save. Such attributes could be set as nullable to allow create blank model.
  • To prevent spam of unkept models in database they could be deleted on a predetermined schedule (once a week for example).
<?php

namespace App\Models;

use Cog\Flag\Traits\Classic\HasKeptFlag;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasKeptFlag;
}

Your model is now can be marked to be kept!

Model must have boolean is_kept column in database table.

By default all records that have a is_kept equals to 0 will be excluded from your query results. To include unkept records, all you need to do is call the withUnkept() method on your query.

Available functions

Get kept + not kept models

Post::all();
Post::withNotKept();

Get only kept models

Post::withoutNotKept();

Get only not kept models

Post::onlyNotKept();

Keep model

Post::whereKey(4)->keep();

Undo model keep

Post::whereKey(4)->undoKeep();

Get unkept models which older than hours

Post::onlyUnkeptOlderThanHours(4);

Output will have all unkept models created earlier than 4 hours ago.