Why a merged namespace is created instead of a submodule? - php

I added my module for creating blanks migration, views, controllers, etc.;
private function createModel()
{
$model = Str::singular(Str::studly(class_basename($this->argument('name'))));
$this->call('make:model',[
'name' => "App\\Modules\\".trim($this->argument('name'))."\\Models\\".$model
]);
}
After running the
php artisan make:module Admin\Users --model --controller
command in the console, I get the wrong structure (pic1)

Related

Laravel Factory State- Unable to locate factory

I have a problem when executing the factory, i have used the factory state for factories but it will give me an error when i execute the factory
https://laravel.com/docs/5.6/database-testing#factory-states
I have this UserFactory.php which contains the code below.
<?php
use Faker\Generator as Faker;
$factory->state(App\User::class,'suggestor', function (Faker $faker) {
return [
'FirstName'=>$faker->firstName,
'LastName'=>$faker->lastName,
'Username'=>$faker->userName,
'password'=>bcrypt('123asd!##'),
'Email'=>$faker->email,
'AccountType'=>0,
];
});
i am using tinker to execute the factory commands and tried different syntax but it really does not solve the problem.
>>> factory(User::class, 1)->states('suggestor')->make();
[!] Aliasing 'User' to 'App\User' for this Tinker session.
InvalidArgumentException with message 'Unable to locate factory with name [default] [User].'
>>> factory(App\User::class, 1)->states('suggestor')->make();
InvalidArgumentException with message 'Unable to locate factory with name [default] [App/User].'
>>> factory(\App\User::class, 1)->states('suggestor')->make();
InvalidArgumentException with message 'Unable to locate factory with name [default] [App/User].'
>>> factory('App\User')->states('suggestor')->make();
InvalidArgumentException with message 'Unable to locate factory with name [default] [App/User].'
>>> factory('App\User',1)->states('suggestor')->make();
InvalidArgumentException with message 'Unable to locate factory with name [default] [App/User].'
>>>
i hope there's anyone out there can help me.
Update:
I have tried running it on database seed but i think it's still the same error.
but when i tried on the other model it seems fine. i think the problem is on the User model which comes out of the box by laravel and note that i haven't change anything on the user model except the model attributes.
error produce by seeder
As the error states, you need a default factory. Please compare the following two:
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->safeEmail,
'password' => bcrypt(str_random(10)),
'remember_token' => $faker->randomNumber(),
];
});
$factory->state(App\User::class, 'test_state', function (Faker\Generator $faker) {
return [
'name' => 'Namoshek',
'email' => 'namoshek#example.com',
];
});
The first definition is the default factory for users, when not giving a state. You can call them with factory(App\User::class, 10)->create() where 10 is optional to give the number of models to create.
You can also chain ->states('test_state') after the call to factory():
factory(App\User::class)->states('test_state')->create(), which will first run the default factory and then apply the changes defined by the given state on the model. But you always need a default factory, otherwise the system doesn't know where and what to apply the state to.
By the way, there is a difference between ->create() and ->make(). The latter does only create the models without persisting them in the database, whereas the first one persists them. So ->create() is equivalent to ->make()->save().
sometimes it also happens that factory works fine in web routes and tests but in tinker it behaves as it is mentioned above. In that case you can try to clear laravel application cache. here are the commmands.
php artisan cache:clear
php artisan config:clear
php artisan route:clear
this will clear all the caches. then i could create model instances using factory.
>>> factory(User::class)->create() // or
>>> factory(Book::class)->create()

Laravel passport install on dynamic database

I am creating database for each client registration in my laravel application. I have installed passport for authorization. I have successfully created database and ran migration for passport also. The passport:install command is not working for newly created database. Is there any way to run command passport:install for my new database.
$this->info(sprintf("Dropping database if exists : %s", $dbName));
DBHelper::drop($dbName);
$this->info("Setting up database for client");
//Create migration table
Artisan::call("migrate:install", array(
"--database" => DBHelper::connect($dbName)
));
//Run migration
Artisan::call('migrate',
array('--path' => 'database/migrations/client',
'--database' => DBHelper::connect($dbName))); //DBHelper::connect($dbName) : Create new database config and then DB::reconnect()
//Install passport migration
Artisan::call('migrate', ['--path' => 'vendor/laravel/passport/database/migrations']);
//Install passport
Artisan::call('passport:install');
//Populate database
Artisan::call('db:seed',
array('--database' => DBHelper::connect($dbName)));
After creating database use bellow commands for creating migrations and install passport.
Artisan::call('migrate:refresh', ['--seed' => true]);
Artisan::call('migrate',['--path' => 'vendor/laravel/passport/database/migrations','--force' => true]);
shell_exec('php ../artisan passport:install');
Usually you would use the following code in your controller to excute an Artisan call:
Artisan::call('passport:install');
However, this doesn't work on passport:install and you will get the error:
There are no commands defined in the "passport" namespace
To fix this you must add the following code to boot method at AppServiceProvider.php :
<?php
namespace App\Providers;
use Laravel\Passport\Console\ClientCommand;
use Laravel\Passport\Console\InstallCommand;
use Laravel\Passport\Console\KeysCommand;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
Passport::routes();
/*ADD THIS LINES*/
$this->commands([
InstallCommand::class,
ClientCommand::class,
KeysCommand::class,
]);
}

how to add an admin in laravel 5.1 auth manually from database

any body has any idea how to pass the authentication of laravel ? or to add an admin from database or the source code ? assuming you have created an admin panel and an admin user but you lost your database and now you just want to create a new admin user for your panel . i used default laravel authentication and middle ware for admin panel . here is the middle ware added in kernel.php
'admin' => \App\Http\Middleware\AuthAdmin::class,
and here we got role controller
if(Auth::user()->isSuperAdmin()) {
$objects = Role::select($this->dt_fields_db)->where('id','<>',1)->where('id','<>',3);
} else {
$objects = Role::select($this->dt_fields_db)->where('id','>',3);
}
Make a new Seeder class, create a user and the super admin role, assign the role to the user and be a super admin forever and ever.
public class SuperAdminSeeder {
public function run () {
// modify to following commands fit your table structure
$role = Role::create(['name' => 'super_admin'];
$user = User::create(['email' => 'your#email.com', 'password' => bcrypt('secret')]);
DB::table('role_user')->insert(['user_id' => $user->id, 'role_id' => $role->id]);
}
}
Call it via the command line:
php artisan db:seed --class=SuperAdminSeeder::class
Just run php artisan make:auth and php artisan migrate. Then, navigate your browser to http://your-app.dev/register or any other URL that is assigned to your application. These two commands will take care of scaffolding your entire authentication system.

Laravel model factories using same seed for testing purposes

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

Unable to use Laravel / Socialite with Lumen

I try to use the package Laravel\Socialite in my system in Lumen (5.1)
I added this in the config\services.php file :
<?php
//Socialite
'facebook' => [
'client_id' => '##################',
'client_secret' => '##################',
'redirect' => 'http://local.dev/admin/facebook/callback',
],
In bootstrap\app.php file :
class_alias(Laravel\Socialite\Facades\Socialite::class, 'Socialite');
$app->register(Laravel\Socialite\SocialiteServiceProvider::class);
Then I created a controller for the facebook authentication :
<?php
namespace App\Http\Controllers\Facebook;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Contracts\Factory as Socialite;
class FacebookController extends Controller
{
public function redirectToProviderAdmin()
{
return Socialite::driver('facebook')->scopes(['manage_pages', 'publish_actions'])->redirect();
}
public function handleProviderCallbackAdmin()
{
$user = Socialite::driver('facebook')->user();
}
}
And in the routes.php :
$app->get('/admin/facebook/login', 'App\Http\Controllers\Facebook\FacebookController#redirectToProviderAdmin');
$app->get('/admin/facebook/callback', 'App\Http\Controllers\Facebook\FacebookController#handleProviderCallbackAdmin');
I just followed the documentation, changing according to my needs. When I go to page http://local.dev/admin/facebook/login, I get the following error :
Non-static method Laravel\Socialite\Contracts\Factory::driver() cannot be called statically, assuming $this from incompatible context
Indeed, according to the code, driver function must be instanciate.
EDIT : And if I try to instanciate this class, I get the following error :
Cannot instantiate interface Laravel\Socialite\Contracts\Factory
How do you make this module to work?
here's how that works in my case
in services.php file
'facebook' => [
'client_id' => '***************',
'client_secret' => '***************',
'redirect' => ""
],
i left redirect empty cause my site is multilingual (so, it fills in a bit later with sessions). if you use only one language, put there your callback absolute path. for example
"http://example.com:8000/my-callback/";
also check your config/app.php. in providers array
Laravel\Socialite\SocialiteServiceProvider::class,
in aliases array
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
my routes look like this
Route::get('facebook', 'Auth\AuthController#redirectToProvider');
Route::get('callback', 'Auth\AuthController#handleProviderCallback');
here's auth controllers methods. put in top
use Socialite;
//იობანი როტ
public function redirectToProvider(Request $request)
{
return Socialite::with('facebook')->redirect();
}
public function handleProviderCallback(Request $request)
{
//here you hadle input user data
$user = Socialite::with('facebook')->user();
}
my facebook app
giga.com:8000 is my localhost (so its the same localhost:8000)
as you can see in Valid OAuth redirect URI, you should put there your callback. in my case i use three urls cause i have three languages. in your case it should be just
http://your-domain-name.com:8000/callback
if you work on localhost, you should name your domain in config/services.php
mine look like this
'domain' => "your-domain.com",
after everything run these commands
php artisan cache:clear
php artisan view:clear
composer dump-autoload
restart your server, clear your browser cookies. hope it helps

Categories