Laravel ships with rich global function which you can use anywhere in application. Still somewhere in application you need few details at anywhere. You want to run specific code at so many conotrollers and blade files.
For that you don't want tp write same code at everytime. You need to create global function which can be used at anywhere in application. You can do it using composer.
In this article, we will create global method and use it in blade view file.
First of open composer.json
file in the root directory of project. Under the "autoload"
key, add files array with php file location as below:
"autoload": {
"files": [
"app/Helpers/helpers.php"
],
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
Now add the helper file at app/Helpers/helpers.php
. In this file we will define a function.
<?php
/*
* Function to convert datetime into human readable format
* timeElapsedString('2013-05-01 00:22:35'); -- 4 months ago
* timeElapsedString('2013-05-01 00:22:35', true); -- 4 months ago
* timeElapsedString('@1367367755'); # timestamp input -- 4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago
*/
if (!function_exists('timeElapsedString')) {
function timeElapsedString($datetime, $full = false)
{
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
}
At the last, we need to add newly created file into composer file list. Run the command in Terminal or CMD to discover new files.
composer dump-autoload
Now you can use timeElapsedString()
method anywhere in the project.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div class="container m-3">
<div class="row">
<p>Launching soon {{ timeElapsedString(date('2021-07-01 23:59:59')) }}</p>
</div>
</div>
</body>
</html>
I hope it will help you.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
How to Get the Current Year using PHP
Use the PHP date() Function You can s...onClick event Handling in React with Example
In this tutorial, we are going to look a...Laravel 5.5 - Login With Only Mobile Number Using Laravel Custom Auth
Today, we are share with you how to modi...How to install and configure Redis server on Ubuntu 20.04
Redis is open source, fast in-memory dat...Laravel 8 CRUD Operation with example from the scratch
CRUD operation is a basic functionality...