SergkeiM
SergkeiM

Reputation: 4168

Laravel Carbon seconds to forHumans

I have a table with column seconds, where I insert online time (in seconds),

Carbon::parse($seconds)->forHumans();

Doesnt allow me to do this, there is a way to parse seconds and transfer it to humans reading? like 1 hour or 2 weeks?

Upvotes: 6

Views: 15477

Answers (3)

Abdelhakim Ezzahraoui
Abdelhakim Ezzahraoui

Reputation: 481

1) php artisan make:middleware LastActivityUser

2) Add this code in middleware LastActivityUser

 <?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Carbon\Carbon;
use Cache;

class LastActivityUser
 {
     /**
     * The authentication factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
     protected $auth;

     /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
     public function __construct(Auth $auth)
     {
         $this->auth = $auth;
     }
     /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check()) {
            $expiresAt = Carbon::now()->addSeconds(10);
            Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
        }
        return $next($request);
    }
}

3) Add This Function in Your User Model

public function is_online() {
        return Cache::has('user-is-online-' . $this->id);
    }

4) Declare in (app\Http\Kernel.php)

protected $middlewareGroups = [
   'web' => [

       \App\Http\Middleware\LastActivityUser::class, //Add this Line
   ]

5) in Your Template Blade

 @if($user->is_online())
   <span>On</span>
 @else 
   <span>Off</span>
 @endif

Upvotes: 0

ArtisanBay
ArtisanBay

Reputation: 1041

Try this:

Carbon Time in Human readable format

// $sec will be the value from your seconds table
echo Carbon::now()->addSeconds($sec)->diffForHumans();
// OR
echo Carbon::now()->subSeconds($sec)->diffForHumans();

Output

// if $sec = 5
5 seconds from now

Found this useful doc Carbon

Hope this is helpful.

Upvotes: 3

Maltronic
Maltronic

Reputation: 1802

This should return the result you're after:

Carbon::now()->subSeconds($seconds)->diffForHumans();

Upvotes: 10

Related Questions