Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added method deleteMeta #587

Open
wants to merge 2 commits into
base: 5.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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