How to generate UUID without dashes (hyphens) in Laravel? - laravel

When generating a UUID in Laravel, It's being generated according to the standard format which includes 4 dashes (hyphens) like this (for example):
51a0cb84-8b3d-43c4-bfd4-8fcef1f360d4
How to generate the UUID in Laravel without dashes or hyphens? like this:
51a0cb848b3d43c4bfd48fcef1f360d4

In Laravel (since version 5.6), you can generate a UUID (version 4) that follows the standard format using the Str::uuid() method:
use Illuminate\Support\Str;
return Str::uuid();
Or, to generates a "timestamp first" UUID that may be efficiently stored in an indexed database column, you may use Str::orderedUuid():
use Illuminate\Support\Str;
return Str::orderedUuid();
And because Laravel actually makes use of ramsey/uuid package to generate the UUID, then generating the UUID in Laravel without dashes or hyphens could be done using the package's getHex() method:
use Illuminate\Support\Str;
return Str::uuid()->getHex();
// OR
return Str::orderedUuid()->getHex();

Related

Update Laravel Migration command to have all common imports and fields in one go for migration file

I have Enums which I am using it in almost all files for migration. Important them one by one is lots of work every time. Is there a way I can modify the template for laravel migration command and add those imports at the start itself and also if possible, the common fields too.
below is not the answer to what I need. Majority of the part of the question is about Auto import the enums file, below is just the part for fields which I have asked but don't think can be accepted as answer as how to add import is missing in the first place.
Can one modify the templates created by artisan migrate command?
Example below:
Default migration file header
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Code I expect for migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\Enums\Role; // added by me
use App\Enums\Status; // added by me
You can use PHP include: include(relative/path/to/fieldsarray.php) and that file will be an array of what you want with something like:
Migration File:
$table->enum('level', include(relative/path/to/fieldsarray.php));
Common File:
<?php
// Current File: relative/path/to/fieldsarray.php
return [
'option1',
'option2',
];

Numbers are formatted as string after scout:import Laravel

I had to use php artisan scout:import command, while I was developing the website in my local environment and everything worked perfectly. However, once I deployed my app and used the same command using ssh I got my model imported, but with int attributes rendered as strings, f.e. 1 was formatted as "1". Because of that, I fail to use numeric_filters. I use the MySql database in both cases.
Numbers are rendered as the string in JSON response by default.
You could either use instructions from this https://stackoverflow.com/questions/31527050/laravel-5-controller-sending-json-integer-as-string or you could use casts attributes in the model so every time model is serialized it will cast respective columns as specified.
E.g. In model, you can define something like this:
protected $casts = [
'something' => 'float'
];

Non-static method Cartalyst\Sentinel\Sentinel::getUser() should not be called statically

Hi I am using laravel Sentinel as my Auth, also I am trying to use laravel auditing I am getting "Non-static method Cartalyst\Sentinel\Sentinel::getUser() should not be called statically".
In my user model I have added a static function resolveId() for adding user_id in Laravel Auditing 'audits' table
public static function resolveId(){
return Sentinel::getUser()->getUserId();
//return auth()->check() ? auth()->user()->getAuthIdentifier() : null;
}
When I try to use \Sentinel::getUser() I am getting the error below.
Non-static method Cartalyst\Sentinel\Sentinel::getUser() should not be called statically
From the docs:
After installing the package, open your Laravel config file located at config/app.php and add the following lines.
In the $aliases array add the following facades for this package.
'Sentinel' => Cartalyst\Sentinel\Laravel\Facades\Sentinel::class,
Then just add this to the top of the class:
use Sentinel;
Put this use on top of the file in question:
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
I'm aware that the package version #manikandan k was asking help for is 4.x or 5.x, and while the documentation does mention the use case for Sentinel, it doesn't provide an actual example.
Since version 6.x, the Audit Resolvers documentation has this very use case, where Sentinel is used instead.
I suggest updating the resolver logic to the following:
return Sentinel::check() ? Sentinel::getUser()->getUserId() : null;
This will prevent calling getUserId() on null, when a user isn't logged.

Laravel 5.3 - how do I set fetchmode in query builder?

I'm working with legacy code. The old report engine uses associative arrays, Laravel's query builder returns an array of objects.
I need to turn objects into arrays. I've tried using:
\DB::connection('tars-test') //->setFetchMode(PDO::FETCH_ASSOC)
but that gets me Class 'App\Http\Controllers\PDO' not found
It's been suggested to put ->all() at the end of the query but that throws error Call to a member function all() on array
The most efficient way would be to set the fetchmode at runtime, for the legacy function and just for the legacy function. How do I do it?
You can use 'toArray' method:
https://laravel.com/docs/5.3/collections#method-toarray
Laravel 5.3 and lower
You went the right way but as you can see laravel is trying to find PDO in App\Http\Controllers\PDO which probably means you forgot to add use Illuminate\Database\PDO;
Laravel 5.4 and up
Since laravel 5.4 this is not an option. But you still can set fetch mode globally: Laravel 5.4 - How to set PDO Fetch Mode?
Or if you still wish to change it just locally:
Return values only (no keys/associative array) in Laravel

Localize date format in Laravel

I am using Laravel 5.2 with Carbon and I trying to get dates in locale format. I mean if I have the date 2015-12-31 in the database, I want it to be printed as 12/31/2015 or 31/12/2015 depends on the user locale.
In the User model I have an attribute locale that presents the user locale. But I don't know who to make it works. I know that Laravel using Carbon for dates, but in the Carbon class I see that the format Y-m-d is hard coded.
I still need the dates will be saved in format Y-m-d and only the presentation will depends on the User->locale attribute.
So how can I achieve that behavior? Is there any way to do that with Carbon itself?
I have solution for you.
Override getAttribute method in your model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use DateFormatting;
protected $dates = [
'finished_at',
// other field names that you need to format
];
public function getAttribute($key)
{
if ( array_key_exists( $key, $this->getDates() ) ) {
// here you can format your date
}
return parent::getAttribute($key);
}
}
after all you can access to this fields as usual(using magic __get())
$model->finished_at;
There is a way to do this using Carbon but it seems like it's really going to vary according to the specs of your server and what not. From reading, it seems like locale packages aren't always consistent. Use locale -a on your production server terminal to check which supported locales you have installed. If you need to install one, use sudo locale-gen <NEW LOCALE>.
But once you have your locale strings sorted out, it seems that you can say
$date = new Carbon;
setlocale('en_GB');
echo $date->formatLocalized('%x'); // '16/06/16'
I derived the %x modifier from the strftime() function, it specifies the format to be "the preferred date representation based on locale, without the time" according to the php manual

Resources