2

I have a boolean field when I try to update from false to true for a single or multiple records it works but when trying to update it back to false it works for the first record only and can not repeat to update multiple records at the same time without refreshing the page 1- my vue component that handles the request is like this:

<template>
<div v-for="(channel, index) in items" :key="channel.id">
<a href="" @click.prevent="toggleVisibility(channel)">
<i v-if="channel.active" class="fas fa-stop default-stop" data-toggle="tooltip" title="Stop Channel"> 
</i>
<i v-else class="fas fa-play" data-toggle="tooltip" title="Start Channel"></i>
</a>
</div>
</template>

export default {
    name: "Channels",
    props: ['allChannels'],
    data() {
        return {
            items: this.allChannels
        }
    },
    methods: {
        toggleVisibility(channel) {
            axios[channel.active ? 'delete' : 'post'](`/visible-channels/${channel.name}`);
        }
    }
}

and my routes:

Route::post('/visible-channels/{channel}', 'ChannelsController@activate');
Route::delete('/visible-channels/{channel}', 'ChannelsController@deactivate');

my controller:

public function activate(Channel $channel, Request $request)
{
    if ($request->method() == 'POST') {
        $channel->update(['active' => true]);
    }
    return back();
}

public function deactivate(Channel $channel, Request $request)
{
    if ($request->method() == 'DELETE') {
        $channel->update(['active' => false]);
    }
}

The model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Channel extends Model
{
protected $guarded = [];

protected $casts = [
    'active' => 'boolean',
];

protected static function boot()
{
    parent::boot(); 

    static::updating(function () {
        return Cache::forget('activeChannels');
    });
}

public function getRouteKeyName()
{
    return 'name';
}
}

2 Answers 2

3

Since laravel stores boolean as 1 and 0 in database, You should probably set active property to boolean in your model

That's because laravel treat false as string so when you set active to false it compares it as 'false' == true which is true so it stores 1 in database.

class Channel extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'active' => 'boolean',
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

0

I figured it out just change in the boot function to wait until the update finish

 static::updated(function () {
    return Cache::forget('activeChannels');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.