Skip to main content

How to use Mutators and Accessors in Laravel?

Mutators and Accessors in Laravel     


Set file path in model

public function getFilePathAttribute($file_path)

    {

        if(!empty($file_path))

        {

             return $filepath = URL::to('/') . '/upload/' . $file_path;

/*             return asset('/upoad/' . $file_path); */


        }

    }

Set created time ago in model

protected $appends = ["created_time_ago"];

public function getCreatedTimeAgoAttribute()

    {

        $created_at = $this->attributes['created_at'];

        // Convert the date/time to a Carbon instance

        $carbonCreatedAt = Carbon::parse($created_at);

        // Get the "time ago" format

        $timeAgo = $carbonCreatedAt->diffForHumans();

        // Set the modified value to the column

        return $timeAgo;

    }

Set created time ago in model

public function getRequestedTimeAttribute($requested_time)

    {

        if(!empty($requested_time))

        {

             return date_format($requested_time,"Y-m-d");

        }

    }

Comments

Popular posts from this blog

How to check date format in PHP?

Check date format in PHP function isCorrectDateFromat($date){     if(!empty($date)){         $dateString = $date; // Replace this with your date string         $format = "Y-m-d"; // Replace this with your expected date format         $dateTime = DateTime::createFromFormat($format, $dateString);         if ($dateTime === false) { /*             echo "The date is not in the correct format."; */         } else {             $errors = DateTime::getLastErrors();             if (empty($errors)) { /*                 echo "The date is in the correct format."; */                 return true;             } else { /*                 echo "...