#how to get difference between two dates in laravel carbon
Explore tagged Tumblr posts
codehunger · 4 years ago
Text
Laravel-find days between two dates in laravel
Laravel-find days between two dates in laravel
In this blog, we will learn about how to find days between two dates in laravel, This tutorial will give you a simple example of getting days difference in laravel. if you want to see an example of how to get days difference in laravel then you are in the right place. Follow the below tutorial step of laravel 8 gets last week’s records from the database. If you want to see what all carbon does…
Tumblr media
View On WordPress
1 note · View note
codingspoint · 3 years ago
Text
How to Get Difference of Time in Minutes in Laravel?
How to Get Difference of Time in Minutes in Laravel?
Today now in this post i will show you How to Get Difference of Time in Minutes in Laravel? Sometimes we may need to calculate minutes difference between the two dates in any version laravel 5, laravel 6, laravel 7 and laravel 8 Application. But In Laravel provide the Carbon class. It Help of Carbon class we can easily simply calculate the minutes difference between the two dates. We can simply…
View On WordPress
0 notes
programmingbiters-blog · 7 years ago
Photo
Tumblr media
New Post has been published on http://programmingbiters.com/laravel-5-how-to-get-unique-page-view-count-for-article-or-post/
Laravel 5 : How To get Unique Page View Count for Article or Post
Today i am going to share very comanly use functionality feature about retrieving and storing page view for your blog post or article.Using this laravel Page View Counter we can use this  powerful, flexible and easy to use laravel package for adding a page view counter to your Eloquent models. It’s designed to be flexible and useful for various projects. Instead of only a simple page view counter, we provide out of the box some great functionalities.
Features
Here are some of the main features:
Store page views
Store page views with expiry dates (history is stored in the users session)
Get the total page views
Get the total page views from a specific date
Get the total page views between a specific date range
Get the total unique page views (by ip address)
Configure date transformers to replace big lines like $article->getPageViewsFrom(Carbon::now()->subDays(1)) to $article->getPageViewsFrom('24h') (’24h’, ‘7d’ etc. is completely configurable).
Installation
Before you can use this package you have to install it with composer.
You can install the package via composer:
composer require cyrildewit/laravel-page-view-counter
Now add the service provider in config/app.php file, or if you’re using Laravel >=5.5, this can be done via the automatic package discovery:
'providers' => [ // ... CyrildeWit\PageViewCounter\PageViewCounterServiceProvider::class, ];
  You can publish the migration with:
php artisan vendor:publish --provider="CyrildeWit\PageViewCounter\PageViewCounterServiceProvider" --tag="migrations"
After publishing the migration file you can create the page visits table by running the migrations:
php artisan migrate
You can publish the config file with:
php artisan vendor:publish --provider="CyrildeWit\PageViewCounter\PageViewCounterServiceProvider" --tag="config"
  Making an Eloquent model viewable
  Here’s an example of a an model :  Article.php
use Illuminate\Database\Eloquent\Model; use CyrildeWit\PageViewCounter\Traits\HasPageViewCounter; class Article extends Model use HasPageViewCounter; protected $appends = ['page_views']; // ...
  Storing new page views
After adding the trait to your model, some methods will be available. addPageView() is one of them. It will simply store a new page view in the database. The best place where you should put it is in your controller.
Put this code in : ArticleController.php
  <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Model\Article; use Carbon\Carbon; //use App\Events\ViewListingHandler; class ArticleController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index($id) $Article = Article::find($id); $Article->addPageView(); // // Stores a new page view in the database //or $Article->addPageViewThatExpiresAt(Carbon::now()->addHours(2)); // // Store a new page view in the database with an expiry date. return view('pages.user.articleview')->with('article',$Article );
  Retrieving page views
Note: Unique page views are getting retrieved differently than the total page views. When calculating the total page views, we are using the aggregate functions of SQL. But the calculation of the unique page views is done by retrieving all the items and count them. If you’re a SQL expert and would like to solve this, thanks!
// Retrieve the total page views pit this line of code in articleview.blade.php
$article->getPageViews(); $article->getUniquePageViews();
// Retrieve page views that are stored after the given date
$article->getPageViewsFrom(Carbon::now()->subWeeks(2)); // since two weeks ago $article->getUniquePageViewsFrom(Carbon::now()->subWeeks(2)); // based upon ip address
// Retrieve page views that are stored before the given date
$article->getPageViewsBefore(Carbon::now()->subWeeks(2)); // upto two weeks ago $article->getUniquePageViewsBefore(Carbon::now()->subWeeks(2)); // based upon ip address
// Retrieve page views that are stored between the given two dates
$article->getPageViewsBetween(Carbon::now()->subMonths(1), Carbon::now()->subWeeks(1)); $article->getUniquePageViewsBetween(Carbon::now()->subMonths(1), Carbon::now()->subWeeks(1)); // based upon ip address
You can also access the total page views now by $article->page_views. This makes the following available:
// Different examples
$articles = Article::all()->sortBy('page_views'); $articles = Article::with('relatedModel')->get()->sortBy('page_views'); $articles = Article::where('status', 'published')->get()->sortBy('page_views');
Configuration
When published, the config/page-view-counter.php config file contains:
use Carbon\Carbon; return [ /* * Our "HasPageViewCounter" trait needs to know which Eloquent model should * be used to retrieve your page views. * * The model you want to use as a PageView model needs to implement the * `CyrildeWit\PageViewCounter\Contracts\PageView` contract. */ 'page_view_model' => CyrildeWit\PageViewCounter\Models\PageView::class, /* * Our "HasPageViewCounter" trait needs to know which table should be used * to retrieve your page views. * * It is used by creating the migrations files and default Eloquent model. */ 'page_views_table_name' => 'page-views', /* * The below key is used by the PageViewHistory class that handles the page * views with expiry dates. Make sure that it's unique. */ 'page_view_history_session_key' => 'page-view-counter.session.history', /* * Register here your custom date transformers. When the package get one of * the below keys, it will use the value instead. * * Keep it empty, if you don't want any date transformers! * * Example: * - $article->getPageViewsFrom('past24hours'); // Get the total page views of the past 24 hours * - $article->getPageViewsFrom('past14days'); // Get the total page views of the past 14 days */ 'date-transformers' => [ // 'past24hours' => Carbon::now()->subDays(1), // 'past7days' => Carbon::now()->subWeeks(1), // 'past14days' => Carbon::now()->subWeeks(2), ], ]; Defining date transformers Because we all love having to repeat less, this package allows you to define date transformers. Let’s say we are using the following code a lot in our blade views: $article->getPageViewsFrom(Carbon::now()->subDays(3)). It can get a little bit annoying and unreadable. Let’s solve that! If you’ve published the configuration file, you will see something like this: 'date-transformers'
  Defining date transformers
Because we all love having to repeat less, this package allows you to define date transformers. Let’s say we are using the following code a lot in our blade views: $article->getPageViewsFrom(Carbon::now()->subDays(3)). It can get a little bit annoying and unreadable. Let’s solve that!
If you’ve published the configuration file, you will see something like this:
'date-transformers' => [ // 'past24hours' => Carbon::now()->subDays(1), // 'past7days' => Carbon::now()->subWeeks(1), // 'past14days' => Carbon::now()->subWeeks(2), ],
  They are all commented out as default. To make them available, simply uncomment them. The provided ones are serving as an example. You can remove them or add your own ones.
For our example, we could do the following:
'date-transformers' => [ 'past3days' => Carbon::now()->subDays(3), ],
  We can now retrieve the page views like this in our blade views:
<p>Page views in past three days $article->getPageViewsFrom('past3days') </p>
0 notes
mbaljeetsingh · 8 years ago
Text
Quick Tip: Display Dates Relatively in Laravel
We have previously looked at the Carbon package by Brian Nesbitt as well as all the functionality it adds to PHP's DateTime class.
In this article, we will take a look at how Laravel takes advantage of this package.
Introduction
As already mentioned, The carbon class does not rebuild PHP's DateTime class from scratch, it builds upon it.
<?php namespace Carbon; class Carbon extends \DateTime { // code here }
This means that you can access the default functionality of PHP's DateTime class on top of the awesomeness that is Carbon.
Laravel already includes the Carbon class by default so we do not need to install it separately. To get started with Carbon in Laravel, simply create a new project using the laravel command.
$ laravel new scotch-dates
Carbon Dating in Laravel
See what I did there? Turns out Brian Nesbitt had the same idea in mind while creating the Carbon package.
Now by default, if the timestamps variable in a Laravel model class is not explicitly set to false, then it is expected that it's corresponding table should have the created_at and updated_at columns.
We can however go ahead and add our own date columns such as activated_at, dob or any other depending on the type of application or the nature of the Laravel model we are working on.
But how does laravel know that these fields should be cast to date?
Simple. Add all the date fields to the protected dates variable in the model class.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ 'created_at', 'updated_at', 'activated_at', 'dob' ]; }
Setup
In our scotch-dates application that we just created, we already have a our first migration setup for the user's table. We will need to have some user records to work with, so let's seed some data in our database with the factory helper method on tinker.
$ php artisan tinker >>> factory('App\User', 10)->create()
To get started, we'll go ahead and create a new UserController class to get all the user's from the user's table into a view and add a /users route.
/routes/web.php
Route::get('/', function () { return view('welcome'); }); Route::get('/users', 'UserController@users');
I have gone ahead to add a few helper variables courtesy of the Carbon class to give me access to a few dates such as now, yesterday, today and tomorrow.
/app/Http/Controllers/UserController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use Carbon\Carbon; class UserController extends Controller { public function users() { return view('users', [ 'users' => User::all(), 'now' => Carbon::now(), 'yesterday' => Carbon::yesterday(), 'today' => Carbon::today(), 'tomorrow' => Carbon::tomorrow() ]); } }
Let's play around with Carbon dates on the user's view.
Displaying Absolute Dates
Having setup our user's details and passed them on to the users view, we can now display each of the users with the following blade template.
<table> <tr> <th>Name</th> <th>Created</th> </tr> @foreach($users as $user) <tr> <td></td> <td></td> </tr> @endforeach </table>
With this, we should have the following.
Displaying Dates Relatively
Displaying dates relatively is quite popular since it is easier for humans to read out a post as created 30 minutes ago as opposed to 2017-01-08 19:15:20.
Let's play around with the Carbon class to see how we can display the dates relatively in different ways.
When comparing a value in the past to default now:
This comes in handy when you want to display a date in the past with reference to the current time. This would be something like:
A few seconds ago
30 minutes ago
2 days ago
1 year ago
To achieve this, we simply use the diffForHumans method.
$user->created_at->diffForHumans() // 1 hour ago
When comparing a value in the future to default now:
You'd probably want to use this in cases where you need to publish a post in the future or show an expiration date.
1 hour from now
5 months from now
$user->created_at->addDays(5)->diffForHumans() //5 days from now
When comparing a value in the past to another value:
1 hour before
5 months before
$yesterday->diffForHumans($today) //1 day before
When comparing a value in the future to another value:
1 hour after
5 months after
$tomorrow->diffForHumans($today) //1 day after
More About Diffs
While it may be nice to display to the user fully quallified diffs such as 2 hours ago, you may at times simply want to show the user the value without the text.
This may come in handy where you have many comments coming in and the text is just too repetitive. diffInSeconds() in particular can be used in cases where the difference in time between two entities, say, lap times, is of significance.
This can achieved by the diffInYears, diffInMonths(), diffInWeeks(), diffInDays(), diffInWeekdays(), diffInWeekendDays() diffInHours(), diffInMinutes() and diffInSeconds() methods.
$user->created_at->diffInHours(); //2 $user->created_at->diffInMinutes(); //134 $user->created_at->diffInSeconds(); //8082
The carbon class also come with methods that return the number of seconds since midnight or to the end of the day (midnight) which can be used to create a countdown, say, for a product sale.
$now->secondsSinceMidnight() //77825 $now->secondsUntilEndOfDay() //8574
Conclusion
There's alot you can achieve with the Carbon class and sometimes you will not find out about a functionality that it provides until you need it.
Take a look at the documentation here. Happy Carbon dating!
via Scotch.io http://ift.tt/2koKYn4
0 notes
codehunger · 4 years ago
Text
Hours difference between two dates in Laravel?
Hours difference between two dates in Laravel?
In this blog, we will see how to get hours difference between two dates in Laravel.Whenever you need to get the difference between two dates in hours in laravel 5 then you can get easily using Carbon. Laravel by default provides the Carbon class. Carbon class through you can calculate the difference between two dates in hours. In the Following example you can see, we have two dates, the first…
Tumblr media
View On WordPress
0 notes