News

Filter a bool with Angular and Laravel

Published

I ran into a situation where I had a table that I needed to allow searching/filtering. Luckily Angular makes this super easy and here is the basic setup:

<input type="text" ng-model="search">
<table>
    <tr ng-repeat="post in posts | filter:search  | orderBy : 'created_at' : true">
    ....

This works great for any fields with text but in my case a post has a dynamic status. It can be either active, draft, or scheduled. The database only stores a boolean for active and then scheduled works against this and a publish_at timestamp.

With this setup you wouldn’t be able to type “active”, “draft”, or “scheduled” in the search to filter. To do this you would either need a custom filter in Angular or you can just set this up with an Eloquent Mutator.

/**
 * Format the status into a string that can be filtered
 *
 * @param $value
 * @return string
 */
public function getStatusAttribute()
{
    if ($this->attributes['active'] )
    {
        if ($this->attributes['publish_at']  >= Carbon::now()->toDateTimeString())
        {
            return 'scheduled';
        }
        return 'active';
    }
    return 'draft';
}

Now you just over ride the parent toArray:

/**
 * Get the model attributes and relationships in array form.
 *
 * @return array
 */
public function toArray()
{
    $array = parent::toArray();

    $array['status'] = $this->getStatusAttribute();

    return $array;
}

Finally when you fetch the JSON you will have a status key in your post object and you can then filter by the strings.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Filed in

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article
Flock: A Free, Native Herd Alternative for Laravel image

Flock: A Free, Native Herd Alternative for Laravel

Read article
Live Props for Real-Time Updates in Inertia.js v3.11 image

Live Props for Real-Time Updates in Inertia.js v3.11

Read article
Cooldown Dependency Policy now in Composer 2.11 image

Cooldown Dependency Policy now in Composer 2.11

Read article
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article