Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel is it bad to use public static functions in controllers [closed]

Is it bad to use public static function in laravel controllers

In my Product model I have a function that look like this:

public static function setEndDate($time)
{
   if ($time == 2)                                                 
   {
         return Carbon::now()->addMonths(2)->toDateTimeString();
   }
   else                                                            
   {
         return Carbon::now()->addDays($time)->toDateTimeString();
   }

}

And then in my controller I use that function like this:

//Validation etc..

$time = Input::get('end_date'); //To transform end-time

$newProduct = new Product();

$newProduct->some_value = Input::get('some_value');
$newProduct->some_value = Input::get('some_value');


$newProduct->end_date = Product::setEndDate($time); //Using my static function like this


newProduct->save();

Is it bad to use static functions like above?

like image 653
user2722667 Avatar asked Oct 24 '25 15:10

user2722667


1 Answers

The question per se is pretty opinion-based. I won't say it's necessarily bad to have methods like these in your model, although I also don't recommend doing it. (For more information about that check out @Colin Schoen's answer)

Anyways, Eloquent offers a much nicer solution for this specific problem of yours: Mutators!

They are kind of "setter methods" in where you can modify or mutate the value that will be assigned to the property. Here's an example:

public function setEndDateAttribute($time){
    if ($time == 2)                                                 
    {
        $this->attributes['end_date'] = Carbon::now()->addMonths(2)->toDateTimeString();
    }
    else                                                            
    {
        $this->attributes['end_date'] = Carbon::now()->addDays($time)->toDateTimeString();
    }
}

And you use it like this:

$newProduct->end_date = $time;
like image 105
lukasgeiter Avatar answered Oct 26 '25 04:10

lukasgeiter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!