Laravel Seeder for Different Environments - laravel

I created two folders in my seeder folder:
/seeds
/local
/production
DatabaseSeeder.php
Then, defined the following inside DatabaseSeeder.php
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
// Load production seeder
if (App::Environment() === 'production')
{
$this->call('production/UsersTableSeeder');
}
// Load local seeder
if (App::Environment() === 'local')
{
$this->call('local/UsersTableSeeder');
}
}
}
Now I know I can't do call('local/UsersTablderSeeder'), and that is my question. How can I call() the seeder files from their respective folders?
Edit
To be clear, when I run the code as it is shown above, I get the following error
[ReflectionException]
Class local/UsersTableSeeder does not exist

I just tried this quickly and got it working, so I'll show you how I set it up and hopefully that helps.
app/database/seeds/local/UsersTableSeeder.php
<?php namespace Seeds\Local;
use Illuminate\Database\Seeder as Seeder;
Class UsersTableSeeder extends Seeder {
public function run () {
dd('local');
}
}
app/database/seeds/production/UsersTableSeeder.php
<?php namespace Seeds\Production;
use Illuminate\Database\Seeder as Seeder;
Class UsersTableSeeder extends Seeder {
public function run () {
dd('production');
}
}
app/database/seeds/DatabaseSeeder.php
<?php
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run(){
Eloquent::unguard();
// Load production seeder
if (App::Environment() === 'production')
{
$this->call('Seeds\Production\UsersTableSeeder');
}
// Load local seeder
if (App::Environment() === 'local')
{
$this->call('Seeds\Local\UsersTableSeeder');
}
}
}
And don't forget to run composer dump-autoload.
Hope that helps.

Laravel 5.7 or higher
if ( App::environment('local') ) {
$this->call(Seeder::class);
}
if ( App::environment('production') ) {
$this->call(Seeder::class);
}
if ( App::environment('testing') ) {
$this->call(Seeder::class);
}

The problem is '/'. You should use '\' instead.

Related

laravel-8 user table seeder does not exist

I am trying to make a login from laravel 8 but at the begging I faced an error which I cannot find a solution. The UsersTablesSeeder is created but still the compiler cannot find it
Illuminate\Contracts\Container\BindingResolutionException
Target class [UsersTablesSeeder] does not exist.
at C:\xampp\htdocs\pary\vendor\laravel\framework\src\Illuminate\Container\Container.php:832
828▕
829▕ try {
830▕ $reflector = new ReflectionClass($concrete);
831▕ } catch (ReflectionException $e) {
➜ 832▕ throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
833▕ }
834▕
835▕ // If the type is not instantiable, the developer is attempting to resolve
836▕ // an abstract type such as an Interface or Abstract Class and there is
1 C:\xampp\htdocs\pary\vendor\laravel\framework\src\Illuminate\Container\Container.php:830
ReflectionException::("Class "UsersTablesSeeder" does not exist")
2 C:\xampp\htdocs\pary\vendor\laravel\framework\src\Illuminate\Container\Container.php:830
ReflectionClass::__construct("UsersTablesSeeder")
the following code shows DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
$this->call(UsersTablesSeeder::class);
}
}
this is my user table
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\User;
class UsersTablesSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
User::create([
'name' => 'John Smith',
'email' => 'john_smith#gmail.com',
'password' => Hash::make('password'),
'remember_token' => str_random(10),
]);
}
}
I am following this link
Add namespace Database\Seeders; to your class. As said in laravel 8
Seeders and factories are now namespaced. To accommodate for these
changes, add the Database\Seeders namespace to your seeder classes. In
addition, the previous database/seeds directory should be renamed to
database/seeders:

How to implement event/listeners with repository pattern in laravel 5.4

I can't make listeners trigger action update, create or delete when I user patter repository.
Addionally I have added my code in order to help my to solve my problem.
TicketController.php
namespace App\Http\Organizer\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Events\Contracts\IEvent;
use App\Entities\Event;
class TicketController extends Controller
{
protected $IEvent;
public function __construct( IEvent $IEvent )
{
$this->IEvent = $IEvent;
}
public function checkFutbolType ($activityId)
{
// I need to listen this action here
$event = $this->IEvent->update(21927, ['title'=>'new title']);
}
}
My RepoEvent.php:
<?php
namespace App\Http\Events\Repositories;
use App\Http\Events\Contracts\IEvent
;
class RepoEvent implements IEvent
{
protected $model;
public function __construct($model)
{
$this->model = $model;
}
public function update($activityId, $params)
{
return $this->model->where('id', $activityId)->update($params);
}
}
My AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Entities\Event;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//event: creating
Event::creating(function (Event $event) {
return $event->creatingEvent();
});
//event: saving
Event::saving(function (Event $event) {
return $event->savingEvent();
});
//event: updating
Event::updating(function (Event $event) {
return $event->updatingEvent();
});
}
}
My interface IEvent.php:
<?php
namespace App\Http\Events\Contracts;
interface IEvent
{
public function update($activityId, $params);
}
My ServicesOrchestration.php:
<?php
namespace App\Http\Administration\Providers;
use App\Entities\Event;
use App\Http\Administration\Repositories\RepoEvent;
use Illuminate\Support\ServiceProvider;
class ServicesOrchestration extends ServiceProvider
{
public function boot()
{
}
public function register()
{
$this->app->bind('App\Http\Administration\Contracts\IEvent', function () {
return new RepoEvent(new Event());
});
}
}
My model Event.php
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
public function creatingUser() {
\Log::info('creating event');
}
public function savingUser() {
\Log::info('saving event');
}
public function updatingUser() {
\Log::info('updating event');
}
}
thanks in advance.thanks in advance.thanks in advance.thanks in advance.thanks in advance.thanks in advance
Here's the relevant snipped from the docs (scroll to mass updates):
When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.
For your code to work you need to first retrieve the actual model instance like below:
public function update($activityId, $params)
{
$instance = $this->model->find($activityId);
$instance->fill($params);
$instance->save();
}
This will have an additional cost of doing two queries instead of one and only being able to update a single model at a time.
A sidenote: You're passing a model instance to the repository but what you actually want is to pass a query builder instance:
$this->app->bind('App\Http\Administration\Contracts\IEvent', function () {
return new RepoEvent(Event::query());
});

Why am I getting an error that rand is not recognized when seeding in laravel

I am trying to run php artisan:migrate --seed for my DatabaseSeeder.php but I keep getting this error in my terminal:
InvalidArgumentException : Unknown formatter "rand"
239| return $this->formatters[$formatter];
240| }
241| }
242| throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter));
243| }
244|
245| /**
246| * Replaces tokens ('{{ tokenName }}') with the result from the token method call
Here is the code from my Database Seeder php
<?php
use App\Question;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
factory(App\User::class, 3)->create()->each(function($u){
$u->questions()
->saveMany(
factory(App\Question::class, rand(1,5))->make()
);
});
}
}
Why am I getting this error?
It may be better to store rand() outside the factory closures.
Try to change your code to:
public function run()
{
$number = rand(1,5);
factory(App\User::class, 3)->create()->each(function($u) use ($number){
$u->questions()
->saveMany(
factory(App\Question::class, $number)->make()
);
});
}

PhpStorm Laravel Dusk w/ a testing database

I currently have PhpStorm running Dusk Test successfully however, I would like it to use the testing database I have set up. Per other threads and resources online, I have created the .env.dusk.local and phpunit.dusk.xml that points to the testing database I have created. When I run the dusk tests in PhpStorm the application that is rendered in Chromium doesn't use the testing database that is described in these files but when I run them using php artisan dusk in the terminal it uses the correct databases.
It seems like I need make phpstorm aware of what env file to use when running the tests. Any clues on how to make this work.
If you're running the tests using artisan dusk, make sure that the APP_ENV setting you are running Dusk in matches the .env.dusk.[environment] setting.
The Dusk browser instance always use the current .env file so...
From the Laravel Dusk docs:
When running tests, Dusk will back-up your .env file and rename your Dusk environment to .env. Once the tests have completed, your .env file will be restored.
If you're not running the artisan dusk command to run your Dusk tests, I suspect that you would have to do something similar to this code before and after running the test suite:
https://github.com/laravel/dusk/blob/2.0/src/Console/DuskCommand.php#L136
If you get this working I'd be very interested in how you did it.
I found this article that works well and describes what the issue is.
https://harings.be/running-laravel-dusk-tests-from-phpstorm-atf2v
tests/DuskTestCase.php
tests/DuskTestCase.php
<?php
namespace Tests;
use Dotenv\Dotenv;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\TestCase as BaseTestCase;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
abstract class DuskTestCase extends BaseTestCase
{
use CreatesApplication;
use DatabaseMigrations;
public static function basePath($path = '')
{
return __DIR__ . '/../' . ($path ? DIRECTORY_SEPARATOR . $path : $path);
}
/**
* Prepare for Dusk test execution.
*
* #beforeClass
* #return void
*/
public static function prepare()
{
static::startChromeDriver();
}
public static function setUpBeforeClass()
{
copy(self::basePath('.env'), self::basePath('.env.backup'));
copy(self::basePath('.env.dusk.local'), self::basePath('.env'));
(new Dotenv(self::basePath()))->overload();
parent::setUpBeforeClass();
}
public static function tearDownAfterClass(): void
{
copy(self::basePath('.env.backup'), self::basePath('.env'));
unlink(self::basePath('.env.backup'));
(new Dotenv(self::basePath()))->overload();
parent::tearDownAfterClass();
}
/**
* Create the RemoteWebDriver instance.
*
* #return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
$options = (new ChromeOptions)->addArguments([
'--disable-gpu',
'--headless',
'--window-size=1920,1080',
]);
return RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY, $options
)
);
}
}
You need to add to DuskTestCase.php something like this:
/**
* #beforeClass
* #return void
*/
public static function prepare()
{
//static::startChromeDriver();
copy(base_path('.env'), base_path('.env.backup'));
copy(base_path('.env.dusk.local'), base_path('.env'));
(new Dotenv(base_path()))->overload();
}
/**
* #afterClass
* #return void
*/
public static function finish()
{
copy(base_path('.env.backup'), base_path('.env'));
unlink(base_path('.env.backup'));
(new Dotenv(base_path()))->overload();
}
Thx Andriy, I improved your code, this works for me :
use Dotenv\Dotenv;
public static function basePath($path = '') {
return __DIR__. '/../' . ($path ? DIRECTORY_SEPARATOR.$path : $path);
}
/**
* Prepare for Dusk test execution.
*
* #beforeClass
* #return void
*/
public static function prepare()
{
copy(DuskTestCase::basePath('.env'), DuskTestCase::basePath('.env.backup'));
copy(DuskTestCase::basePath('.env.dusk.local'), DuskTestCase::basePath('.env'));
(new Dotenv(DuskTestCase::basePath()))->overload();
static::startChromeDriver();
}
public static function closeAll()
{
copy(DuskTestCase::basePath('.env.backup'), DuskTestCase::basePath('.env'));
unlink(DuskTestCase::basePath('.env.backup'));
(new Dotenv(DuskTestCase::basePath()))->overload();
return parent::closeAll();
}
..since base_path() and finish() weren't working in this DuskTestCase class
This worked for me
<?php
namespace Tests;
use Dotenv\Dotenv;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\TestCase as BaseTestCase;
abstract class DuskTestCase extends BaseTestCase
{
use CreatesApplication;
public static function basePath($path = '') {
return __DIR__. '/../' . ($path ? DIRECTORY_SEPARATOR.$path : $path);
}
// [ ... ]
public static function setUpBeforeClass(): void
{
if (file_get_contents(self::basePath('.env')) !== file_get_contents(self::basePath('.env.dusk.local'))) {
copy(self::basePath('.env'), self::basePath('.env.backup'));
}
copy(self::basePath('.env.dusk.local'), self::basePath('.env'));
Dotenv::createMutable(self::basePath())->load();
parent::setUpBeforeClass();
}
public static function tearDownAfterClass(): void
{
copy(self::basePath('.env.backup'), self::basePath('.env'));
unlink(self::basePath('.env.backup'));
Dotenv::createMutable(self::basePath())->load();
parent::tearDownAfterClass();
}
// [ ... ]
}
Found it at https://github.com/laravel/dusk/issues/883

Target [App\Http\Controllers\IndexController] is not instantiable. in laravel

I have cloned project from github and installed in my local system everything is working fine.
And i created controller through command, the controller is created but when i try to use controller function the error shows me like below.
BindingResolutionException
Target [App\Http\Controllers\SomeController] is not instantiable.
in Container.php (line 895)
I tried to solve this problem by running command below:
php artisan cache:clear
php artisan clear-compiled
composer dump-autoload
php artisan optimize
php artisan config:clear
But i still got same error. Kindly help me to resolve this issue.
My controller is:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SomeController extends Controller
{
public function getIndex() {
echo "string";
}
}
AppServiceProvider.php :
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Carbon\Carbon;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected function __construct() {
$variable2 = "I am Data 2";
View::share ( 'variable2', $variable2 );
}
protected function create_permission($role_type_id,$module_id)
{
$CheckCreatePermission = \DB::table('role_type_access')->where(['role_type_id'=> $role_type_id,'module_id'=>$module_id])->select('create')->get();
if(!empty($CheckCreatePermission[0]))
{
if($CheckCreatePermission[0]->create===1)
{
return 1;
}
return 0;
}
return 0;
}
protected function edit_permission($role_type_id,$module_id)
{
$CheckEditPermission = \DB::table('role_type_access')->where(['role_type_id'=> $role_type_id,'module_id'=>$module_id])->select('edit')->get();
if(!empty($CheckEditPermission[0]))
{
if($CheckEditPermission[0]->edit===1)
{
return 1;
}
return 0;
}
return 0;
}
protected function delete_permission($role_type_id,$module_id)
{
$CheckDeletePermission = \DB::table('role_type_access')->where(['role_type_id'=> $role_type_id,'module_id'=>$module_id])->select('delete')->get();
if(!empty($CheckDeletePermission[0]))
{
if($CheckDeletePermission[0]->delete===1)
{
return 1;
}
return 0;
}
return 0;
}
protected function view_permission($role_type_id,$module_id)
{
$CheckViewPermission = \DB::table('role_type_access')->where(['role_type_id'=> $role_type_id,'module_id'=>$module_id])->select('view')->get();
if(!empty($CheckViewPermission[0]))
{
if($CheckViewPermission[0]->view===1)
{
return 1;
}
return 0;
}
return 0;
}
protected function view_all_permission($role_type_id,$module_id)
{
$CheckLayoutPermission = \DB::table('role_type_access')
->join('modules', 'role_type_access.module_id', '=', 'modules.id')
->where(['role_type_access.role_type_id'=> $role_type_id,'role_type_access.view'=>1,'role_type_access.module_id'=>$module_id])
->select('role_type_access.module_id','role_type_access.view','role_type_access.create','role_type_access.edit','role_type_access.delete','modules.name','modules.label')->get();
return $CheckLayoutPermission;
// print_R($$CheckViewMenuPermission);
// echo count($CheckViewMenuPermission);
/* if(!empty($CheckViewPermission[0]))
{
if($CheckViewPermission[0]->view===1)
{
return 1;
}
return 0;
}
return 0;*/
}
public function getDownload($file_path,$file_name)
{
//PDF file is stored under project/public/download/info.pdf
$file= public_path().'/uploads/'.$file_path.'/'.$file_name;
$headers = array(
'Content-Type: application/pdf',
);
return \Response::download($file, $file_name, $headers);
}
public function updateTracker($tracked_date,$action)
{
$Globaltracks = \DB::table('global_tracks')->where('tracked_date', $tracked_date)->get();
if (count($Globaltracks) > 0) {
\DB::table('global_tracks')
->where('tracked_date', $tracked_date)
->increment($action,1,['updated_at'=>Carbon::now()->toDateTimeString()]);
} else {
$Globaltracks_id = \DB::table('global_tracks')->insert(
['tracked_date' => $tracked_date,$action => 1,'created_at'=>Carbon::now()->toDateTimeString()]);
}
}
}
Change Your Constructor Access Modifier to Public. It solve my problem.
public function __construct() {
$variable2 = "I am Data 2";
View::share ( 'variable2', $variable2 );
}
Update your SomeController with the below code:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class SomeController extends Controller
{
public function getIndex() {
echo "string";
}
}

Resources