kandi background

Carbon | A simple PHP API extension for DateTime. | Date Time Utils library

 by   briannesbitt PHP Version: 2.57.0 License: MIT

 by   briannesbitt PHP Version: 2.57.0 License: MIT

Download this library from

kandi X-RAY | Carbon Summary

Carbon is a PHP library typically used in Utilities, Date Time Utils applications. Carbon has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can download it from GitHub.
An international PHP extension for DateTime. https://carbon.nesbot.com.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • Carbon has a medium active ecosystem.
  • It has 15715 star(s) with 1206 fork(s). There are 229 watchers for this library.
  • There were 2 major release(s) in the last 6 months.
  • There are 7 open issues and 1113 have been closed. On average issues are closed in 11 days. There are 3 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of Carbon is 2.57.0
Carbon Support
Best in #Date Time Utils
Average in #Date Time Utils
Carbon Support
Best in #Date Time Utils
Average in #Date Time Utils

quality kandi Quality

  • Carbon has 0 bugs and 0 code smells.
Carbon Quality
Best in #Date Time Utils
Average in #Date Time Utils
Carbon Quality
Best in #Date Time Utils
Average in #Date Time Utils

securitySecurity

  • Carbon has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • Carbon code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
Carbon Security
Best in #Date Time Utils
Average in #Date Time Utils
Carbon Security
Best in #Date Time Utils
Average in #Date Time Utils

license License

  • Carbon is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
Carbon License
Best in #Date Time Utils
Average in #Date Time Utils
Carbon License
Best in #Date Time Utils
Average in #Date Time Utils

buildReuse

  • Carbon releases are available to install and integrate.
  • Installation instructions are not available. Examples and code snippets are available.
Carbon Reuse
Best in #Date Time Utils
Average in #Date Time Utils
Carbon Reuse
Best in #Date Time Utils
Average in #Date Time Utils
Top functions reviewed by kandi - BETA

kandi has reviewed Carbon and discovered the below as its top functions. This is intended to give you an instant insight into Carbon implemented functionality, and help decide if they suit your requirements.

  • Returns a formatted date for the calendar .
  • Create a date from ISO format .
  • Returns the ISO units .
  • Add a unit to this instance .
  • Translates time string .
  • Returns whether this instance matches the given Tester .
  • Changes the week of the year .
  • Fix negative microseconds
  • Returns the region name .
  • Set the settings .

Carbon Key Features

A simple PHP API extension for DateTime.

Carbon Examples and Code Snippets

  • Carbon
  • With Composer
  • Without Composer
  • Laravel eloquent not fetching the data properly
  • Remove text which is displayed on bars in plotly bar chart
  • PHP Carbon does not calculate the time difference
  • Datatable order by Month and Year
  • Laravel Eloquent when date condition
  • python transpose a dataframe and group and append new columns
  • Rounding the corners of an SVG
  • Pass dynamic value from database to Carbon::now()->subMinutes()
  • How can I prevent an extra level from being added when naming categorical levels in terra SpatRaster?
  • How can I determine if this week is the first week of the month? (Preferably with Carbon)

Carbon

<?php

use Carbon\Carbon;

printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver'));  //implicit __toString()
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
$nextSummerOlympics = Carbon::createFromDate(2016)->addYears(4);

$officialDate = Carbon::now()->toRfc2822String();

$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;

$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');

$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');

// Don't really want this to happen so mock now
Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));

// comparisons are always done in UTC
if (Carbon::now()->gte($internetWillBlowUpOn)) {
    die();
}

// Phew! Return to normal behaviour
Carbon::setTestNow();

if (Carbon::now()->isWeekend()) {
    echo 'Party!';
}
// Over 200 languages (and over 500 regional variants) supported:
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'
echo Carbon::now()->subMinutes(2)->locale('zh_CN')->diffForHumans(); // '2分钟前'
echo Carbon::parse('2019-07-23 14:51')->isoFormat('LLLL'); // 'Tuesday, July 23, 2019 2:51 PM'
echo Carbon::parse('2019-07-23 14:51')->locale('fr_FR')->isoFormat('LLLL'); // 'mardi 23 juillet 2019 14:51'

// ... but also does 'from now', 'after' and 'before'
// rolling up to seconds, minutes, hours, days, months, years

$daysSinceEpoch = Carbon::createFromTimestamp(0)->diffInDays();

Community Discussions

Trending Discussions on Carbon
  • Laravel eloquent not fetching the data properly
  • Remove text which is displayed on bars in plotly bar chart
  • PHP Carbon does not calculate the time difference
  • Datatable order by Month and Year
  • Laravel Eloquent when date condition
  • python transpose a dataframe and group and append new columns
  • Rounding the corners of an SVG
  • Pass dynamic value from database to Carbon::now()->subMinutes()
  • How can I prevent an extra level from being added when naming categorical levels in terra SpatRaster?
  • How can I determine if this week is the first week of the month? (Preferably with Carbon)
Trending Discussions on Carbon

QUESTION

Laravel eloquent not fetching the data properly

Asked 2022-Apr-11 at 09:03

In my laravel vue application I have two tables, user table and user_document table.

In my user_document table, I have a column called, added_by.

This column stores the ids of the users.

There are two roles in my app, admins and general users.

My users can upload documents to the system via vue component. Admin can upload documents for other users as well.

And users can view their already uploaded document details in a datatable.

In that datatable, I'm displaying a column called, Added By, which shows the users who uploaded the document(the user him self or by the admin).

I have following controller to fetch and display those records.

<?php

namespace App\Http\Controllers\Dashboard\Corporate\Employee;

use App\Company;
use App\Models\OtherDocument;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CompanyEmployeeOtherDocumentsController extends Controller
{
    /**
     * @param string $locale
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(string $locale, Company $company, User $user)
    {

        $otherDocuments = OtherDocument::where('user_id', $user->id)
            ->with('added_by_user')
            ->when(request('validity_status'), function ($query) {
                $query->where(function ($query) {
                    $query->when( in_array('active', request('validity_status')), function ($query) {
                        $query->where(function (Builder $query) {
                            $query->whereDate('issued_at', '<=', Carbon::now())
                                ->whereDate('expires_at', '>=', Carbon::now()->addMonth());
                        })->orWhere('is_valid_forever',1);
                    })->when( in_array('expires', request('validity_status')), function ($query) {
                        $query->orWhere(function (Builder $query) {
                            $query->whereDate('expires_at', '<=', Carbon::now()->addMonth())
                                ->whereDate('expires_at', '>=', Carbon::now());
                        });
                    })->when( in_array('expired', request('validity_status')), function ($query) {
                        $query->orWhereDate('expires_at', '<', Carbon::now());
                    });
                });
            })
            ->when(request('search_text'), function ($query) {
                $query->where('name', 'like', '%' . request('search_text') . '%');
            })
            ->paginate(request('per_page',config('statguru.pagination.limit')));

        for ($i=0; $i < count($otherDocuments); $i++) {
            $addedByUser = $otherDocuments[$i]->added_by_user;
            if ($addedByUser) {
                $otherDocuments[$i]['added_user_name'] = $addedByUser->first_name . ' ' . $addedByUser->last_name;
            }
        }

        return  response()->json($otherDocuments);

    }
}

And in my vue component I have following header array,

HeaderArray() {
            return [
                {text: 'Certificate', value: 'certificate'},
                {text: 'Added by', value: 'added_by_user_name'},
                {text: 'Institute', value: 'institute'},
                {text: 'Expiration', value: 'valid_date', classList: 'text-center'},
                {text: 'Validity', value: 'validity_status', classList: 'text-center'},
                {text: 'Verification', value: 'verification_status', classList: 'text-center'},
            ];
        },

This whole solution works perfectly.

But now instead of using this for loop

for ($i=0; $i < count($otherDocuments); $i++) {
                $addedByUser = $otherDocuments[$i]->added_by_user;
                if ($addedByUser) {
                    $otherDocuments[$i]['added_user_name'] = $addedByUser->first_name . ' ' . $addedByUser->last_name;
                }
            }

I'm trying to get the same result via eloquent

->with(['added_by_user' => function($q){
                $q->select('first_name', 'last_name');
             }]) 

When I replace the for loop with this, it does not show me the Added by user's first name.... Where do I need to change in the eloquent to fetch that data correctly?

I'm using laravel 9

Update

I have updated my code according to the Malkhazi Dartsmelidze answer below.

Yet I am not being able to display the name on the datatable.

Following is my updated controller,

<?php

namespace App\Http\Controllers\Dashboard\Corporate\Employee;

use App\Company;
use App\Models\OtherDocument;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CompanyEmployeeOtherDocumentsController extends Controller
{
    /**
     * @param string $locale
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(string $locale, Company $company, User $user)
    {

        $otherDocuments = OtherDocument::where('user_id', $user->id)
        ->with(['added_by_user' => function($q){
            $q->select('id', DB::raw('CONCAT(first_name, " ", last_name) as added_user_name'));
        }]) 
            ->when(request('validity_status'), function ($query) {
                $query->where(function ($query) {
                    $query->when( in_array('active', request('validity_status')), function ($query) {
                        $query->where(function (Builder $query) {
                            $query->whereDate('issued_at', '<=', Carbon::now())
                                ->whereDate('expires_at', '>=', Carbon::now()->addMonth());
                        })->orWhere('is_valid_forever',1);
                    })->when( in_array('expires', request('validity_status')), function ($query) {
                        $query->orWhere(function (Builder $query) {
                            $query->whereDate('expires_at', '<=', Carbon::now()->addMonth())
                                ->whereDate('expires_at', '>=', Carbon::now());
                        });
                    })->when( in_array('expired', request('validity_status')), function ($query) {
                        $query->orWhereDate('expires_at', '<', Carbon::now());
                    });
                });
            })
            ->when(request('search_text'), function ($query) {
                $query->where('name', 'like', '%' . request('search_text') . '%');
            })

            ->paginate(request('per_page',config('statguru.pagination.limit')));

        return  response()->json($otherDocuments);

    }
}

and following is the vue header array,

 HeaderArray() {
            return [
                {text: 'Certificate', value: 'certificate'},
                {text: 'Added by', value: 'added_user_name'},
                {text: 'Institute', value: 'institute'},
                {text: 'Expiration', value: 'valid_date', classList: 'text-center'},
                {text: 'Validity', value: 'validity_status', classList: 'text-center'},
                {text: 'Verification', value: 'verification_status', classList: 'text-center'},
            ];
        },

And following is the data I recieve

{
      "id": 6,
      "user_id": 941,
      "added_by": 869,
      "name": "driving licence",
      "issued_at": "2022-04-06T22:00:00.000000Z",
      "expires_at": "2022-04-29T22:00:00.000000Z",
      "is_valid_forever": 0,
      "document_url": null,
      "document_number": null,
      "file_name": "6-driving-licence.pdf",
      "url": "users/941/other-documents/6-driving-licence.pdf",
      "status": "EXPIRES",
      "created_at": "2022-04-07T03:39:47.000000Z",
      "updated_at": "2022-04-07T03:39:47.000000Z",
      "deleted_at": null,
      "expires_at_formatted": "30-04-2022",
      "validity_status": "EXPIRES",
      "remaining_days": 18,
      "added_by_user": {
        "id": 869,
        "added_user_name": "Satya Nadella",
        "country_code": null,
        "formatted_date_of_birth": "2022-04-11",
        "name": " ",
        "company_role": "admin",
        "profile_image": [
          {
            "url": "/img/statguru-user.png"
          }
        ],
        "inviter_user": "",
        "country": null,
        "media": [
          
        ]
      }
    },

ANSWER

Answered 2022-Apr-11 at 09:03

You are doing it wrong here:

->with(['added_by_user' => function($q){
    $q->select('first_name', 'last_name');
}]) 

The way relationship is working is that laravel loops trough result of that query and matches users.id to user_documents.added_by each other and if matches then attaches it.

Since you have selected only first_name and last_name columns, id of it always is null and not matches any user_documents.

Solution:

->with(['added_by_user' => function($q){
    $q->select('id', 'first_name', 'last_name');
}]) 

More convenient way to get full name:

use Illuminate\Support\Facades\DB;
...
->with(['added_by_user' => function($q){
    $q->select('id', DB::raw('CONCAT(first_name, " ", last_name) as added_user_name'));
}]) 

Edit:

Since front end requres that added_user_name should be in the first level of object, you should either map through results and move added_user_name to first level, or join users table and get result from it: But if you are using pagination it's not recommended to use map solution. I'll write only using join

Using join:

Remove ->with function from query and replace it with join.

OtherDocument::where('user_id', $user->id)
    ->join('users', 'users.id', '=', 'user_document.added_by') // do not know exact names of columns
    ->select(DB::raw('user_document.*'), DB::raw('CONCAT(first_name, " ", last_name) as added_user_name'))
    ->...

Source https://stackoverflow.com/questions/71824268

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install Carbon

You can download it from GitHub.
PHP requires the Visual C runtime (CRT). The Microsoft Visual C++ Redistributable for Visual Studio 2019 is suitable for all these PHP versions, see visualstudio.microsoft.com. You MUST download the x86 CRT for PHP x86 builds and the x64 CRT for PHP x64 builds. The CRT installer supports the /quiet and /norestart command-line switches, so you can also script it.

Support

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

DOWNLOAD this Library from

Explore Related Topics

Build your Application

Share this kandi XRay Report

Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit