I'm following a tutorial from Code Forest an when using php artisan db:seed, I get this error:
PHP Fatal Error: Class 'Sentry' not found in /var/www/app/database/seeds/SentrySeeder.php on line 13
here is SentrySeeder.php :
<?php
use App\Models\User;
class SentrySeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
DB::table('groups')->delete();
DB::table('users_groups')->delete();
Sentry::getUserProvider()->create(array(
'email' => 'admin#admin.com',
'password' => "admin",
'first_name' => 'John',
'last_name' => 'McClane',
'activated' => 1,
));
Sentry::getGroupProvider()->create(array(
'name' => 'Admin',
'permissions' => array('admin' => 1),
));
// Assign user permissions
$adminUser = Sentry::getUserProvider()->findByLogin('admin#admin.com');
$adminGroup = Sentry::getGroupProvider()->findByName('Admin');
$adminUser->addGroup($adminGroup);
}
}
And here is User model
Sentry has been added to apps under providers
What Am i missing?
Have you added the Facade for Sentry?
add
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry',
to the array of facades in config/app.php
Add 'Cartalyst\Sentry\SentryServiceProvider' to the list of service providers in app/config/app.php
I had to add both in app/config/app.php file:
1.
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry',
to the: 'aliases' => array(
AND
2.
Cartalyst\Sentry\SentryServiceProvider,
to the: 'providers' => array(
Related
I have laravel project used for apis(Passport). It uses multiple databases one database stores user information and the database name for that user. I created a BaseController, all the other controllers extends from this controller. But I am not able to fetch Auth::id(); from the BaseController. How can I get the Auth::id in the constructor?
class BaseController extends Controller
{
protected $companySchema;
public function __construct() {
$user = \App\User::where('user_id', Auth::id())->first();
$company = $user->company;
$this->companySchema = $company->cmp_Schema;
}
}
After laravel 5.3.4 you can't use Auth::user() in the constructor because the middleware isn't run yet.
class BaseController extends Controller {
public function __construct() {
$this->middleware(function ($request, $next) {
$this->companySchema = Auth::user()->company->cmp_Schema;
return $next($request);
});
}
}
try this code and tell me if it works
You cannot use Auth in constructor, because middleware is not run yet. its from 5.3
check this link : https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors
First you should setup a connection in config/database.php:
'my_new_connection' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => $your_db_name,
'username' => $your_db_username,
'password' => $your_db_password,
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
Then you can change default database connection dynamically by this:
Config::set('database.default', 'my_new_connection');
You should first call
$user = Auth::user();
which is returning you the current user model associated, which is normally User. Then following should work:
$user->id
I had user migration:
$table->enum('type',['seller','buyer'])->default('seller');
I want when using ModelFactory how to get random value seller or buyer?
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'firstName' => $faker->name,
'lastName' => $faker->name,
'username' => $faker->unique()->username,
'email' => $faker->unique()->safeEmail,
'password' => md5('user123'),
'bio' => $faker->sentence(3, true),
'type' => ???,
];
});
Make use of randomElement method
'type' => $faker->randomElement(['seller', 'buyer']),
Laravel version >= 5.6
use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 4 - (retrieved randomly)
"type" => Arr::random($array);
Just in case that anyone is looking for the answer of this question with newer version of Laravel and PHP, you can utilize the enum in PHP like so:
<?php
namespace App\Enums;
enum UserTypeEnum: string
{
case SELLER = 'seller';
case BUYER = 'buyer';
}
and then your factory will look like this:
<?php
namespace Database\Factories;
use App\Enums\UserTypeEnum;
use Illuminate\Database\Eloquent\Factories\Factory;
class TaskFactory extends Factory
{
public function definition()
{
return [
'firstName' => fake()->firstName,
'lastName' => fake()->lastName,
'username' => fake()->unique()->username,
'email' => fake()->unique()->safeEmail,
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password,
'bio' => fake()->sentence(3, true),
'type' => fake()->randomElement(UserTypeEnum::cases()),
];
}
}
And also if your type column is nullable you can have your seeder type like fake()->randomElement([...UserTypeEnum::cases(), null]) as well.
Attached Image shows exact my problem:
Given below is my app.php where providers array is defined.****This is laravel 4.2.
'providers' => array(
'Illuminate\Foundation\Providers\ArtisanServiceProvider',
'Illuminate\Auth\AuthServiceProvider',
'Illuminate\Cache\CacheServiceProvider',
'Illuminate\Session\CommandsServiceProvider',
'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider',
'Illuminate\Routing\ControllerServiceProvider',
'Illuminate\Cookie\CookieServiceProvider',
'Illuminate\Database\DatabaseServiceProvider',
'Illuminate\Encryption\EncryptionServiceProvider',
'Illuminate\Filesystem\FilesystemServiceProvider',
'Illuminate\Hashing\HashServiceProvider',
'Illuminate\Html\HtmlServiceProvider',
'Illuminate\Log\LogServiceProvider',
'Illuminate\Mail\MailServiceProvider',
'Illuminate\Database\MigrationServiceProvider',
'Illuminate\Pagination\PaginationServiceProvider',
'Illuminate\Queue\QueueServiceProvider',
'Illuminate\Redis\RedisServiceProvider',
'Illuminate\Remote\RemoteServiceProvider',
'Illuminate\Auth\Reminders\ReminderServiceProvider',
'Illuminate\Database\SeedServiceProvider',
'Illuminate\Session\SessionServiceProvider',
'Illuminate\Translation\TranslationServiceProvider',
'Illuminate\Validation\ValidationServiceProvider',
'Illuminate\View\ViewServiceProvider',
'Illuminate\Workbench\WorkbenchServiceProvider',
'FanzoopMain\Theme\Provider\ThemeServiceProvider',
'Creolab\LaravelModules\ServiceProvider',
'FanzoopMain\Menu\MenuServiceProvider',
'FanzoopMain\Image\ImageServiceProvider',
'FanzoopMain\Hook\HookServiceProvider',
/**
* App base
*/
'App\Providers\ConfigurationServiceProvider',
'App\Providers\AddonServiceProvider',
'App\Providers\PhotoServiceProvider',
'App\Providers\AdmincpServiceProvider',
'App\Providers\ThemeManagerServiceProvider',
'App\Providers\NotificationServiceProvider',
'App\Providers\MentionServiceProvider',
'App\Providers\HashtagServiceProvider',
'App\Providers\MenuServiceProvider',
'App\Providers\EmoticonServiceProvider',
'App\Providers\ConnectionServiceProvider',
'App\Providers\PostServiceProvider',
'Artdarek\OAuth\OAuthServiceProvider',
'Maatwebsite\Excel\ExcelServiceProvider',
),
/*
|--------------------------------------------------------------------------
| Service Provider Manifest
|--------------------------------------------------------------------------
|
| The service provider manifest is used by Laravel to lazy load service
| providers which are not needed for each request, as well to keep a
| list of all of the services. Here, you may set its storage spot.
|
*/
'manifest' => storage_path().'/meta',
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => array(
'App' => 'Illuminate\Support\Facades\App',
'Artisan' => 'Illuminate\Support\Facades\Artisan',
'Auth' => 'Illuminate\Support\Facades\Auth',
'Blade' => 'Illuminate\Support\Facades\Blade',
'Cache' => 'Illuminate\Support\Facades\Cache',
'ClassLoader' => 'Illuminate\Support\ClassLoader',
'Config' => 'Illuminate\Support\Facades\Config',
'Controller' => 'Illuminate\Routing\Controller',
'Cookie' => 'Illuminate\Support\Facades\Cookie',
'Crypt' => 'Illuminate\Support\Facades\Crypt',
'DB' => 'Illuminate\Support\Facades\DB',
'Eloquent' => 'Illuminate\Database\Eloquent\Model',
'Event' => 'Illuminate\Support\Facades\Event',
'File' => 'Illuminate\Support\Facades\File',
'Form' => 'Illuminate\Support\Facades\Form',
'Hash' => 'Illuminate\Support\Facades\Hash',
'HTML' => 'Illuminate\Support\Facades\HTML',
'Input' => 'Illuminate\Support\Facades\Input',
'Lang' => 'Illuminate\Support\Facades\Lang',
'Log' => 'Illuminate\Support\Facades\Log',
'Mail' => 'Illuminate\Support\Facades\Mail',
'Paginator' => 'Illuminate\Support\Facades\Paginator',
'Password' => 'Illuminate\Support\Facades\Password',
'Queue' => 'Illuminate\Support\Facades\Queue',
'Redirect' => 'Illuminate\Support\Facades\Redirect',
'Redis' => 'Illuminate\Support\Facades\Redis',
'Request' => 'Illuminate\Support\Facades\Request',
'Response' => 'Illuminate\Support\Facades\Response',
'Route' => 'Illuminate\Support\Facades\Route',
'Schema' => 'Illuminate\Support\Facades\Schema',
'Seeder' => 'Illuminate\Database\Seeder',
'Session' => 'Illuminate\Support\Facades\Session',
'SSH' => 'Illuminate\Support\Facades\SSH',
'Str' => 'Illuminate\Support\Str',
'URL' => 'Illuminate\Support\Facades\URL',
'Validator' => 'Illuminate\Support\Facades\Validator',
'View' => 'Illuminate\Support\Facades\View',
'OAuth' => 'Artdarek\OAuth\Facade\OAuth',
'Addon' => 'App\Facades\Addon',
'ThemeManager' => 'App\Facades\ThemeManager',
'Excel' => 'Maatwebsite\Excel\Facades\Excel',
),
This is my another file, named ConfigurationServiceProvider.php, where I am using the error occuring code.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Providers\ConfigurationServiceProvider;
/**
* Configuration service provider
*
* #author : Tiamiyu waliu kola
* #webiste: procrea8.com
*/
class ConfigurationServiceProvider extends ServiceProvider
{
public function register(){
}
public function boot(){
if (\Config::get('system.installed')) {
$repository = app('App\Repositories\ConfigurationRepository');
foreach($repository->getAll() as $configuration) {
\Config::set($configuration['slug'], $configuration['value']);
}
/**
* set image configuration
*/
\Config::set('image::max-size', \Config::get('image-max-size'));
\Config::set('image::save-original', \Config::get('keep-original-image'));
\Config::set('image::allow-animated-gif', \Config::get('allow-animated-gif'));
\Config::set('image::ext-allowed', \Config::get('image-allow-type', 'gif,png,jpg'));
/**Assets***/
\Config::set('theme::minifyAssets', \Config::get('minify-assets'));
}
}
}
Try
composer dump-autoload
Or
php artisan dump-autoload
Make sure you have registered your providers directory on composer.json
"autoload": {
"classmap": [
"app/providers"
]
},
Tty this steps
Temporary remove your providers and aliases
Type command composer update
Then add this providers and aliases
Because when you update composer he try to find this classes before adding in your project, After updating your composer add this classes
Below is my model factory.
$factory->define(App\Business::class, function (Faker\Generator $faker){
return [
'name' => $faker->bs,
'slug' => $faker->slug,
'address' => $faker->streetAddress,
'phone_no' => $faker->phoneNumber,
'mobile_no' => $faker->phoneNumber,
'email' => $faker->companyEmail,
'website' => $faker->domainName,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude,
'location' => $faker->city,
'business_days_from' => $faker->dayOfWeek,
'business_days_to' => $faker->dayOfWeek,
'description' => $faker->text,
'user_id' => $faker->factory(App\User::class),
];
});
and This my database seeder class
class DatabaseSeeder extends Seeder
{
public function run()
{
factory(App\Business::class, 300)->create();
}
}
But when I execute php artisan db:seed ...it does not work..
What should be the workaround here..any help would be appreciated..
you can get all ids using pluck (lists is depricated for laravel >= 5.2)
$userIds = User::all()->pluck('id')->toArray();
and get a random id for FK column:
'user_id' => $faker->randomElement($userIds)
You may also attach relationships to models using Closure attributes in your factory definitions.
'title' => $faker->title,
'content' => $faker->paragraph,
'user_id' => function () {
return factory(App\User::class)->create()->id;
}
I just found the workaround .. I replaced
'user_id' => $faker->factory(App\User::class),
with
'user_id' => $faker->randomElement(User::lists('id')->toArray()),
and that solves the problem for now..
I was wondering if someone can help me.
I am having trouble seeding a database in laravel using seeder, it keeps throughing this error:
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
When running php artisan db:seed
the seeder in question is: GroupTableSeeder.php and the code in the file is:
<?php
class GroupTableSeeder extends Seeder {
public function run()
{
DB::table('groups')->truncate();
$permissions = array( 'system' => 1, );
$group = array(
array(
'name' => 'agency',
'permissions' => $permissions,
'created_at' => new DateTime,
'updated_at' => new DateTime
),
);
DB::table('groups')->insert($group);
}
}
In the DatabaseSeeder.php I have:
public function run()
{
Eloquent::unguard();
$this->call('GroupTableSeeder');
$this->command->info('Group table seeded!');
}
I am trying to populate the Groups table with a user role I am currently using https://cartalyst.com/manual/sentry#groups
Any help would be much appreciated.
Cheers,
Chris
Found the answer, I needed to do:
Sentry::getGroupProvider()->create(array(
'name' => 'Agency',
'permissions' => array('admin' => 1),
));
Instead of:
$permissions = array( 'system' => 1, );
$group = array(
array(
'name' => 'agency',
'permissions' => $permissions,
'created_at' => new DateTime,
'updated_at' => new DateTime
),
);