I am using vinkla/hashids and i have followed the following steps
composer require vinkla/hashids
Add the service provider to config/app.php in the providers array
If you want you can use the facade. Add the reference in config/app.php to your aliases array.
php artisan vendor:publish this step does not create hashid.php in config file
use Vinkla\Hashids\Facades\Hashids;
Hashids::encode(4815162342);
And i get error that hashids class not found
It seems that the provider is not booting.
Try to do this:
php artisan config:clear
php artisan clear-compiled
The first will clear any cached config files, and the later will clear the services cache.
It worked for me, hope it works for you too.
I found the solution here: Laravel 5.2 Service provider not booting
Try checking inside your $laravelSite/config Directory to see if you find a file called hashids.php...
In your Controller; try also to import the the Hashids Class manually like so:
<?php
namespace App\Http\Controllers;
use Vinkla\Hashids\Facades\Hashids;
class SampleClass extends {
public function testHashID(){
$h1 = Hashids::encode(4815162342);
var_dump($h1);
$h2 = Hashids::decode('oaobgb-rnar');
var_dump($h2);
}
}
And by the way; if you don't see hashids.php within your $laravelSite/config Directory; you may try to manually create it. The file just returns an array of Configuration Settings... the content to the file looks like so:
/*
* This file is part of Laravel Hashids.
*
* (c) Vincent Klaiber <hello#vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
/*
|--------------------------------------------------------------------------
| Default Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the connections below you wish to use as
| your default connection for all work. Of course, you may use many
| connections at once using the manager class.
|
*/
'default' => 'main',
/*
|--------------------------------------------------------------------------
| Hashids Connections
|--------------------------------------------------------------------------
|
| Here are each of the connections setup for your application. Example
| configuration has been included, but you may add as many connections as
| you would like.
|
*/
'connections' => [
'main' => [
'salt' => 'your-salt-string',
'length' => 'your-length-integer',
'alphabet' => 'your-alphabet-string',
],
'alternative' => [
'salt' => 'your-salt-string',
'length' => 'your-length-integer',
'alphabet' => 'your-alphabet-string',
],
],
];
To encode just do this
\Hashids::encode($characters)
And to decode
\Hashids::decode($characters)
Related
I want to add to my Lumen project a daily Log.
I try this in the app.php (Folder Bootstrap/)
$logFile = 'laravel.log';
Log::useDailyFiles(storage_path().'/logs/'.$logFile);
But this set me that error
Call to undefined method Monolog\logger::useDailyFiles()
Any help I appreciate...Thanks
If you look at the framework source code here you can see that it will not do daily logs, but rather write to a single log file lumen.log. There is a public method available configureMonologUsing seen here and referenced here that you can use to override the default behavior without extending the Application.
Lumen just sets a handler to monolog, so another good solution is you could do this:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
class LogServiceProvider extends ServiceProvider
{
/**
* Configure logging on boot.
*
* #return void
*/
public function boot()
{
$maxFiles = 5;
$handlers[] = (new RotatingFileHandler(storage_path("logs/lumen.log"), $maxFiles))
->setFormatter(new LineFormatter(null, null, true, true));
$this->app['log']->setHandlers($handlers);
}
/**
* Register the log service.
*
* #return void
*/
public function register()
{
// Log binding already registered in vendor/laravel/lumen-framework/src/Application.php.
}
}
Then don't forget to add the service provider to your Lumen bootstrap/app.php:
$app->register(\App\Providers\LogServiceProvider::class);
In Lumen 5.6 better way is to configure your default setting in .env as LOG_CHANNEL=daily
By default the setting is LOG_CHANNEL=stack which use single file for logging.
Starting from version 5.6, configuring the logging system is much easier:
Create directory config in your project if it doesn't exist
Copy the logging config file from
vendor/laravel/lumen-framework/config/logging.php to your project config dir
Edit file config/logging.php and adjust the channels property to your liking.
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
],
I am trying to set up a default seed for Faker in Laravel which is normally achieved in this way (not in Laravel):
<?php
$faker = Faker\Factory::create();
$faker->seed(1234);
according to Faker's GitHub page.
I am trying to do this so that can I get the same data generated each time so that I can write some unit tests but I have no idea how to do that in Laravel. I've checked Laravel's documentation and tried googling the issue but I found nothing.
Here's how to do apply the seed to Faker in Laravel 5.
Inside your app/database/factories directory, create a new file. I called mine SeedFactory.php.
<?php
$factory->faker->seed('1');
That's it!
Now you have consistent random data for your unit testing!
NB: If you only have one or two factories, you could append that line to an existing factory file.
Here's why it works.
When Laravel processes all the files in the app/database/factories directory, it executes them straightaway. The $factory object passed around is an instance of Illuminate\Database\Eloquent\Factory.php, which keeps with it it's own internal Faker\Generator instance.
Also, you won't need to worry about the naming of the file or execution order, because this will get fired before any of the factory callbacks (assuming you did it as instructed in the Laravel docs).
it is easy. Just define a factory. Let's have a look at the default factory shipped
with laravel 5.5
File: database/factories/ModelFacotry.php
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** #var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
// Add this line to original factory shipped with laravel.
$faker->seed(123);
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});
Then use tinker to test it:
yudu#YududeMacBook-Pro ~/demo> php artisan tinker
Psy Shell v0.8.1 (PHP 7.1.8 — cli) by Justin Hileman
>>> $user = factory(App\User::class)->make()
=> App\User {#880
name: "Jessy Doyle",
email: "jalen86#example.net",
}
>>> $user = factory(App\User::class)->make()
=> App\User {#882
name: "Jessy Doyle",
email: "lbode#example.org",
}
Laravel Docs:
how to define and use factory
Seeding
After days of searching, I have decided to come here and ask.
I have used the package before, and literally copy-pasted the code but it still wont work in this project.
I am trying to use the Elasticquent package for Elasticsearch in laravel 5.2.
The error I get is: Invalid argument supplied for foreach()
This is being thrown in the /vendor/elasticsearch/elasticsearch/src/Elasticsearch/ClientBuilder.php file on line 111.
This happens whenever I try to use the package (ie: using search, addAllToIndex, etc.).
From what I can tell, the config is null, so maybe there is a setting in the elasticquent that I missed?
Any ideas on how to fix this?
EDIT
My config/elasticquent.php file (exact same as `vendor/elasticquent/elasticquent/src/config/elasticquent.php):
<?php
return array(
/*
|--------------------------------------------------------------------------
| Custom Elasticsearch Client Configuration
|--------------------------------------------------------------------------
|
| This array will be passed to the Elasticsearch client.
| See configuration options here:
|
| http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_configuration.html
*/
'config' => [
'hosts' => ['localhost:9200'],
'retries' => 1,
],
/*
|--------------------------------------------------------------------------
| Default Index Name
|--------------------------------------------------------------------------
|
| This is the index name that Elastiquent will use for all
| Elastiquent models.
*/
'default_index' => 'my_custom_index_name',
);
EDIT 2
The result to curl -XGET localhost:9200:
{
"name" : "Mac Gargan",
"cluster_name" : "elasticsearch",
"version" : {
"number" : "2.3.2",
"build_hash" : "b9e4a6acad4008027e4038f6abed7f7dba346f94",
"build_timestamp" : "2016-04-21T16:03:47Z",
"build_snapshot" : false,
"lucene_version" : "5.5.0"
},
"tagline" : "You Know, for Search"
}
EDIT 3
For anyone with this issue, I didn't manage to solve it. I had to use another package mustafaaloko/elasticquent5 found here
Here is my answer in Invalid argument supplied for foreach()
I look into source code and find the problem is that the config doesn't commit as expected, so you can clear cache and publish vendor, this work for me
php artisan config:clear
php artisan cache:clear
php artisan vendor:publish
I have followed zizac/entrust installation tutorial from GitHub Link and faced with error:
Class name must be a valid object or a string in
var/www/html/laravel_test/vendor/zizaco/entrust/src/commands/MigrationCommand.php
on line 86
MigrationCommand.php file url : Link
Outut:
php artisan entrust:migration
Tables: roles, role_user, permissions, permission_role
A migration that creates 'roles', 'role_user', 'permissions', 'permission_role' tables will be created in database/migrations directory
Proceed with the migration creation? [Yes|no] (yes/no) [yes]: yes
Creating migration...
PHP Fatal error: Class name must be a valid object or a string in /var/www/html/laravel_test/vendor/zizaco/entrust/src/commands/MigrationCommand.php on line 86
the command: php artisan vendor:publish was successful.
File : config/entrust.php exist.
I didin't change any options to config/auth.php file same as - auth.php. How to fix it?
in vendor/zizaco/entrust/src/commands/MigrationCommand.php on line 86
remove line :
$usersTable = Config::get('auth.table');
$userModel = Config::get('auth.model');
add line :
$usersTable = Config::get('auth.providers.users.table');
$userModel = Config::get('auth.providers.users.model');
and config/auth.php file write provider line as like me :
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
'table' => 'users',
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
then your problem will solve : happy coding
In vendor/zizaco/entrust/src/commands/MigrationCommand.php on line 86.
Laravel 5.1.* Add Line
$usersTable = Config::get('auth.table');
$userModel = Config::get('auth.model');
Laravel 5.2.* Add Line
$usersTable = Config::get('auth.providers.users.table');
$userModel = Config::get('auth.providers.users.model');
The accepted answer may fix the problem but it is very bad practice to edit direct vendor files. The following will fix the issue you may be having and will support your app still working if you decide to update Entrust and they fix their codebase.
Add the following lines to config/auth.php underneath:
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
Laravel 5.1 - 5.4
'model' => \App\Models\User::class,
'table' => 'users',
Once Entrust rolls out an update you can remove this or keep it. Up to you.
Try running:
php artisan config:cache
to make sure your application is using fresh config files
EDIT
Ok, now I see, this library want to use:
$usersTable = Config::get('auth.table');
$userModel = Config::get('auth.model');
but there is no something like this in auth any more.
So as temporary workaround you should probaby add table and model to auth file like so: https://github.com/laravel/laravel/blob/5.1/config/auth.php
and wait until Entrust will be upgraded to remove this
I want to change the Laravel 5.1 storage path: something like /home/test/storage. This has the advantage that these files are not stored in the repository, which is fairly ugly I think.
In Laravel 4, this was very simple with bootstrap/paths.php.
In Laravel 5, it works by using $app->useStoragePath('/path/') in bootstrap/app.php. However, I want to define the storage path with a config option, like $app->useStoragePath(config('app.storage_path'). The config option calls an environment variable or returns a default location.
Doing this results in a Uncaught exception 'ReflectionException' with message 'Class config does not exist'; this makes sense, because this function is not loaded yet.
I tried setting the storage path just after booting:
$app->booted(function () use ($app) {
$app->useStoragePath(config('app.storage_root'));
});
This changed nothing. I also tried directly binding it to path.storage:
$app->bind('path.storage', function ($app) {
return config('app.storage_root');
});
The last option works partially; the view cache is now placed in the correct location, but the logs are still at the old location.
Set it up in .env
app.php
'app_storage' => env('APP_STORAGE', storage_path()),
app/Providers/AppServiceProvider.php
public function register()
{
$this->app->useStoragePath(config('app.app_storage'));
}
.env
APP_STORAGE=custom_location
Laravel 5.3 is in bootstrap/app.php
/*
|--------------------------------------------------------------------------
| Set Storage Path
|--------------------------------------------------------------------------
|
| This script allows us to override the default storage location used by
| the application. You may set the APP_STORAGE environment variable
| in your .env file, if not set the default location will be used
|
*/
$app->useStoragePath( env( 'APP_STORAGE', base_path() . '/storage' ) );
Here is a simple solution of changing the storage path in Laravel 5 like we do in Laravel 4
on bootstrap/app.php
# new storage path
# base_path() -> returns root path
$path_storage = base_path() . "../../storage";
# override already $app->storagePath using the function
$app->useStoragePath($path_storage);
this will make the storage path to be same with the session, views, cache, logs
This works on Laravel 5.2
File: app/Providers/AppServiceProvider.php
public function register() {
...
$this->app->useStoragePath(config('what_ever_you_want'));
...
}
Calling useStoragePath on your AppServiceProvider wouldn't do the job properly because the AppServiceProvider is called after the config files are loaded. so any use of storage_path in config files would still refer to the old storage path.
In order to properly solve this problem I suggest you extend Application class and then on the constructor of your own class write the followings.
/**
* MyApplication constructor.
*/
public function __construct($basePath = null)
{
parent::__construct($basePath);
// set the storage path
$this->afterLoadingEnvironment(function () {
$this->useStoragePath(/*path to your storage directory*/);
});
}
if your website is hosted;
move everything from public folder to root folder
$app->bind('path.public', function() {
return __DIR__;
});
add this code in your bootstrap/app.php :
$app->useStoragePath(__DIR__ . '/../custom-path/');
and in config/filesystem.php :
'local' => [
'driver' => 'local',
'root' => storage_path('everything'), //custom-path/everything
],
'public' => [
'driver' => 'local',
'root' => storage_path(''),
'url' => env('APP_URL'),
'visibility' => 'public',
],
and then run php artisan config:cache
This works on Laravel 5.8 because you have to load the environment variables before you try to use them.
File: bootstrap/app.php
$app->afterLoadingEnvironment(function() use ($app) {
$app->useStoragePath(env('APP_STORAGE', storage_path()));
});