Numbers are formatted as string after scout:import Laravel - 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'
];

Related

Two models, two fields, return preferred if present

Been struggling with how to do this the most optimized way possible...
I have two models: Catalog and Application.
Catalog has a field called name.
Application has a field called name.
Both have a relationship with each other.
I am struggling to find a way to create a function i could use across my Laravel application which i would pass application.id to it and it would return a $app->name value based on the following logic:
if $application->name exists, use this value as the $app->name for the $application object
otherwise, get the $catalog->name value and use it as the $app->name
Note that I would like to create a component #application() where i can simply pass the $application->id and build the display logic (theming/styling) into it.
Since i display this $app->name in many places, i would like to make it as lightweight as possible to avoid unnecessary queries.
I hope this makes sense! There are probably so many ways to go with it, i am lost at figuring out the way way to do this :(
I'm not completely sure to understand your model/DB design, but you could use a custom Helper to use that function through the whole app.
For that, you can create a simple PHP class Helper.php file in app/Http/Helpers folder or whatever location you want. Something like:
<?php
use App\Catalog;
use App\Application;
if (! function_exists('getAppName')) {
function getAppName($id){
// Do your logic here to return the name
$catalog = Catalog::find($id);
return $catalog->name;
}
}
?>
Then in any controller or view, you just do
getAppName($application->id)
Do no forget to add your helpers file to the composer autoload. So in composer.json in Laravel's root folder, add the helper path to the autoload array:
"files": [
"app/Http/Helpers/helpers.php"
],
Last but not least, run the following command:
composer dump-autoload
Please note that function logic is just for sample purposes since I don't know your model structure.
In my opinion, I care about the database cost.
Use ternary expression will be elegant. But it took two times IO costs from database if application name is empty.
$app_name = Application::find($id)->name;
$app_name = empty($app_name) ? Catalog::where('application_id', $id)->first()->name;
And this will more complicated, but the catalog_query only execute when application.name is empty, it execute in database and the result is taken out only once;
And Database will only find the name from one table or two table.
Something like this:
$catalog_query = Catalog::where('catalogs.application_id', $id)->select('catalogs.name')->groupBy('catalogs.name');
// if catalogs and applications relationship is 1:1, use ->limit(1) or remove groupBy('name') is better.
Application::where("applications.id", $id)
->selectRaw("IF(application.name IS NULL OR application.name = '', (" . $catalog_query->toSql() ."), applications.name ) AS app_name")
->mergeBindings($catalog_query->getQuery())
->first()
->app_name;
Hope this will help you.

Laravel call method on any artisan command

Is it possible to set a method that changes a value in my database automatically when I run a php artisan command? What I'm trying to accomplish is change the value of the first row in my "domains" table to suit the url from my .env file automatically whenever I push codes to my live/staging environment. Are there any ways to do this automatically without me manually going into my DB and changing it.
You could setup a Listener for the native event CommandFinished and check if the command is the config:cache.
Event::listen('Illuminate\Console\Events\CommandFinished', function ($event) {
if ($event->command == 'config:cache') {
// Change domains table data using Eloquent or Query Builder
}
});
To learn more about Events, see: https://laravel.com/docs/5.7/events#generating-events-and-listeners

how to define time Field in laravel nova admin panel

i have time column in my data base . i need to defined field for this column.
this is my migration:
$table->date('date');
$table->time('time_begin');
$table->time('time_Enable');
this is my resource:
public function fields(Request $request)
{
return [
datetime::make('time_Enable'),
datetime::make('time_begin'),
];
}
i just need time not date and time
Impressively enough, Nova not only doesn't have a Time field but also doesn't support a time-only usage of DateTime field.
On the other side, Nova has plenty of third parties componentes that can be easily added via composer. I did look for some on Nova Packages and found two viable options: Laraning Time Field and Michielfb Time Field, they seem to be pretty good and open-source.
Nonetheless, they have relatively few stars on GitHub and a rather old latest version, which is not much of a problem for such a simples functionality, but I'd rather go with a native one, so here is how I implemented it:
Text::make('Duration')
->placeholder('##:##:##')
->rules('date_format:"H:i:s"')
->help('hh:mm:ss'),
So basically I used the Text field with a format validation. Also added the placeholder and help attributes to make it a bit more intuitive. It works well! and I'm using it with a time database field. Other colleges suggested using a masked component but it would also require a third party one and I didn't find a good option.
From the docs
You may customize the display format of your DateTime fields using the format method. The format must be a format supported by Moment.js:
DateTime::make('time_Enable')->format('H mm'),
DateTime::make('time_begin')->format('H mm'),
You can use the extraAttributes option with type key:
Text::make('time_begin')->withMeta(['extraAttributes' => ['type' => 'time']])

Laravel 5.5 Update of Empty Date String Produces Data Missing Carbon Error

The update to Laravel 5.5 seems to be creating a few oddities for me. Probably something I've screwed up, but these issues only broke with the new version - this same code has not failed in 5.4, 5.3, etc. The bigger problem is that the error is not consistent on the same model - it fails on update, but works on store.
I have a date field called 'decom_date' on a 'prog' model with the $dates field on the model overridden to include 'decom_date'. A user can fill out a form for a new 'prog', and skip the 'decom_date' field. The model saves with no error. If the user edits the same prog model with the exact same form, and leaves the 'decom_date' field blank, the following error occurs in Laravel 5.5 only:
message "Data missing"
exception "InvalidArgumentException"
file "/var/www/ipfast/vendor/nesbot/carbon/src/Carbon/Carbon.php"
line 582
IE Carbon is now expecting a format instead of an empty string upon updates only. I can work around this with a mutator on the model like so:
public function setDecomDateAttribute($value)
{
$this->attributes['decom_date'] = $value ?: null;
}
No problem - this works, and I think will stop the new breaking 100%... but I worry when things suddenly break, especially as it doesn't seem consistent across the saves. This pattern fails consistently across every model I have with dates, and these were not broken before update.
Anyone able to shed some light on this - or maybe just something dumb I've done?
I can't confirm this behaviour. If your date is an empty string it always fails with your posted error, no matter if it is during update or create.
Normally in Laravel 5.4 and 5.5 the global middleware stack contains:
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
You can check this in app\Http\Kernel.php
With this middleware emptry strings shoul automatically be converted to a NULL value which Carbons handles properly.
What I can imagine is, that your decom_date field is not even present in the request data when you 'skip' this field during create ( Just check it with dd($request) all on top of your store method.
And if you leave the field 'blank' during your update method, the result is an empty string ( In case the middleware mentioned above is missing ... )

Laravel 4.2 use Sentinel with Jenssegers MongoDB

Is it possible to use Cartalyst/Sentinel with Jenssegers/MongoDB on Laravel 4.2?
I'm currently using Sentry, but I want to try Sentinel with new features.
After installation, I tried this:
$user = Sentinel::register([
'email' => $email,
'password' => $password,
]);
But I've got the following error:
Argument 2 passed to Illuminate\Database\Query\Builder::__construct()
must be an instance of Illuminate\Database\Query\Grammars\Grammar,
null given, called in
/home/vagrant/shared/muzza/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
on line 1853 and defined
Sentinel doesn't have integration with Jenssegers MongoDB lib.
Dan Syme commented on 2 Jul:
You would have to write the implementations for the different models
used throughout Sentinel.
Then switch out the models for the different entities on the config
file with your own implementations, Sentinel should take care of
everything else.
Maxime-BHA commented on 3 Jul:
As #jenssegers already did for Sentry package, you have to create your
own Models extending the originals models from Sentinel and bind the
attributes defined in those models for relationships/persistances to
the new models etc.. like static $usersModel =
'Cartalyst\Sentinel\Users\EloquentUser'; and also change the config
file.
See exemple for Sentry there :
https://github.com/jenssegers/laravel-mongodb-sentry
I think it's the exact same procedure.
More information you can find here.

Resources