Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ochirach's avatar

Using PHP functions in view

Hi,

I have a php function (named 'weeks_in_month') that calculates and returns the number of weeks in a month (parameters: month,year). I want to use this functions result within the view i.e

$number_of_weeks_in_current_month = weeks_in_month($current_month_number, $current_year);

There are $number_of_weeks_in_current_month week(s) in this month

How can I go about this? Is a new controller needed for this? or is this a job for Service Injection? This views controller currently has the 1 function to return the view from a get request.

I will want to store globally used functions like these within a single file for future use

0 likes
4 replies
kishanbhatt's avatar

Hi @ochirach

It's better to use Carbon for date and time operations in laravel.

You can check this, you will find the answer.

http://carbon.nesbot.com/

You can use directly in laravel controller by simply doing this,

use Carbon\Carbon;

gator's avatar

I would just use a static function on a class - store the class in your psr-4 loaded space.

ochirach's avatar

Great! There are about 3 methods from the link but creating the Helper and recording in composer file seems the best solution. Thanks

Please or to participate in this conversation.