0

I have the following query in web.php which is called from use App\Models\clocks as Clock;

Route::get('/clock/{user_id}', function($user_id) {
    $clocks = Clock::find($user_id);

    $user = User::where('id', '=', $clocks->user_id)->first();
    echo 'User: ' . $user->name . '<br />';
    echo 'user_id: ' . $clocks->user_id . '<br />';
    echo 'timestamp: ' . $clocks->timestamp . '<br />';
    echo 'title: ' . $clocks->title . '<br />';
    echo 'timer amended? ' . $clocks->timerAmended . '<br />';
    echo 'description: ' . $clocks->description . '<br />';
    echo 'time amended: ' . $clocks->amendedTime . '<br />';
    echo 'original time: ' . $clocks->unamendedTime . '<br />';
    echo 'total time: ' . $clocks->totalSeconds . '<br />';
});

I also have the following in the model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class clocks extends Model
{
    protected $table = 'clocks';

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

    public function user() {
        return $this->hasOne('App\Models\User');
    }
}

Now, in the laravel docs, in order to output boolean as "true" or "false", a mutator is required, which I have placed in the model for timerAmended.

However, in the view, it is still displaying as an integer. (see timer amended? below):

User: Chauncey Walsh
user_id: 1
timestamp: 1623423462
title: Call with client
timer amended? 1
description: Strategic meeting
time amended: 120
original time: 1000
total time: 1120

Any tips on what I should do?

Beaumont
  • 313
  • 5
  • 16
  • If you echo a boolean, it outputs 1 or 0. not the words true or false... you can echo the words if you want. `. ($clocks->timerAmended ? 'true' : 'false') . ` – Gert B. Aug 24 '21 at 08:12
  • php handles bools as 0 and 1, however the cast should be reflected if you output the response as json – Frnak Aug 24 '21 at 08:23
  • There are many way to echo bool values [PHP - Get bool to echo false when false](https://stackoverflow.com/q/4948663/10517770) – Rahul Jat Aug 24 '21 at 11:01

1 Answers1

0

Good afternoon, you are using "Cast" and not "Mutators". In your case, I would suggest adding the following function to the model.

public function getTimerAmendedAttribute($value): string
{
    return $value === 0 ? 'false' : 'true';
}

You can read more about mutators in the official documentation at the link.

https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator

  • I would not do this because it will result in if statements that will always be true. for example `if($object->timer_amended) { ... ` This case string 'false' will cause the code in the if to run, where it should not. You could make a `getDisplayTimerAmendedAttribute` function instead, that is used for displaying only. – Gert B. Aug 25 '21 at 06:00