Skip to content

Commit

Permalink
Added method deleteMeta
Browse files Browse the repository at this point in the history
  • Loading branch information
kayobruno committed Oct 20, 2021
1 parent 55ad395 commit 39750f3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,16 @@ $postMeta = $post->createMeta('foo', 'bar'); // instance of PostMeta class
$trueOrFalse = $post->saveMeta('foo', 'baz'); // boolean
```

You can delete any metadata:

```php
$post = Post::find(1);
$post->saveMeta('foo', 'baz');

$post->deleteMeta('foo'); // true
$post->deleteMeta('bar'); // false
```

### Querying Posts by Custom Fields (Meta)

There are multiples possibilities to query posts by their custom fields (meta) by using scopes on a `Post` (or another other model which uses the `HasMetaFields` trait) class:
Expand Down
12 changes: 12 additions & 0 deletions src/Concerns/MetaFields.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,4 +214,16 @@ public function getMeta($attribute)

return null;
}

/**
* @param string $key
* @return bool
* @throws \Exception
*/
public function deleteMeta($key): bool
{
$meta = $this->meta()->where('meta_key', $key)->first();

return $meta ? $meta->delete() : false;
}
}
10 changes: 10 additions & 0 deletions tests/Unit/Model/Meta/PostMetaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,16 @@ public function test_higher_order_functions_can_be_executed()
$this->assertEquals($post->meta->one, 'two');
}

public function test_its_value_can_be_removed()
{
$post = factory(Post::class)->create();
$post->saveMeta('foo', 'bar');

$this->assertFalse($post->deleteMeta('bar'));
$this->assertTrue($post->deleteMeta('foo'));
$this->assertFalse($post->deleteMeta('foo'));
}

/**
* @return PostMeta
*/
Expand Down

0 comments on commit 39750f3

Please sign in to comment.