-
-
Notifications
You must be signed in to change notification settings - Fork 21
Keepable model
Anton Komarev edited this page Mar 24, 2020
·
3 revisions
Keep functionality required when you are trying to attach related models before parent one isn't persisted in application.
Issue:
- User press
Create Post
button. - Create post form has image uploader.
- On image uploading user can't attach image to post before post entity wouldn't been stored in database.
Solution:
- Add
HasKeptFlag
trait to model (and add booleanis_kept
column to model's database table). - Create empty model on form loading (it will has
is_kept = 0
by default). - Feel free to add any relations to the model.
- 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.
Post::all();
Post::withNotKept()->get();
Post::withoutNotKept()->get();
Post::onlyNotKept()->get();
Post::whereKey(4)->keep();
Post::whereKey(4)->undoKeep();
Post::onlyUnkeptOlderThanHours(4);
Output will have all unkept models created earlier than 4 hours ago.