Lumen: Generate Model validation rules - laravel

Artisan generator seems over-sophisticated, It generates a class extended from Model class!!!
Is there any way to generate model validation rules in a lumen model automatically (based on column definition of a mysql table)?
What about column names?

I am the author of lumen-generators, A collection of generators for Lumen and Laravel 5.
This package contains a Model Generator which supports generating validation rules.
Installation
Add the generators package to your composer.json by running the command:
composer require wn/lumen-generators
Then add the service provider in the file app/Providers/AppServiceProvider.php like the following:
public function register()
{
if ($this->app->environment() == 'local') {
$this->app->register('Wn\Generators\CommandsServiceProvider');
}
}
Don't forget to include the application service provider on your bootstrap/app.php and to enable Eloquent and Facades if you are using Lumen
If you run the command php artisan list you will see the list of added commands:
wn:controller Generates RESTful controller using the RESTActions trait
wn:controller:rest-actions Generates REST actions trait to use into controllers
wn:migration Generates a migration to create a table with schema
wn:model Generates a model class for a RESTfull resource
wn:pivot-table Generates creation migration for a pivot table
wn:resource Generates a model, migration, controller and routes for RESTful resource
wn:resources Generates multiple resources from a file
wn:route Generates RESTful routes.
Generating a model with validation rules
Runing the following command:
php artisan wn:model TestingModel --rules="name=required age=integer|min:13 email=email|unique:users,email_address"
Will generate a model containing the following rules:
public static $rules = [
"name" => "required",
"age" => "integer|min:13",
"email" => "email|unique:users,email_address",
];
Please refer to the Full README for more details.
Hope this helps :)

There is no such command built into laravel or lumen.
I found a package (on a site called google) that provides such a command: https://github.com/jijoel/validation-rule-generator
It's locked to illuminate/support 4.0.x, so won't work with current versions of laravel. If you have lots of models it might be worth to fork, bump the version in composer.json and see if it works.

Related

Custom Variable in AppServiceProvider Laravel 5.5?

I want use a variable from my database to set a folder for custom views.
"class AppServiceProvider extends ServiceProvider"
$ActiveProject = ThemeConfig::where('module_type',"project")->where('active',"1")->first()->file;
After this, I get an active project name (like Nshop), and I want to set it in:
public function register()
{
$this->app['view']->addNamespace('Projects', base_path() . '/Projects/'.$ActiveProject.'/Views');
}
But I get an error.
How can I accomplish this task?
Using ORM Models in the AppServiceProvider doesn't work. This file is part of the boot process of Laravel where your models are not loaded yet. But you can rely on functions that are part of the Laravel core concept.
$ActiveProject = ThemeConfig::where('module_type',"project")->where('active',"1")->first()->file;
Becomes
$ActiveProject = \DB::table('theme_configs')->where('module_type',"project")->where('active',"1")->first()->file;

Auth0 Login ServiceProvider

I follow up this tutorial using Laravel 5.4 Creating your first Laravel app and adding authentication
But I can't retrieve Auth0 users, the registration works fine in my dashboard new users are created in Auth0 server, but not in my local database and also I can't dd(Auth0::getUser());
I get this error:
Class 'Auth0\Login\LoginServiceProvider' not found
I've added this
Auth0\Login\LoginServiceProvider::class
in my provider array and
'Auth0' => Auth0\Login\Facade\Auth0::class
in my aliases.
I did all steps on configuration from Auth0 docs: Auth0 PHP (Laravel) SDK
I'm out off option now!
Ok, figure it out now.
The error was coming from 'AppServiceProvider.php'
Just import those two classes in AppServiceProvider.php as:
use Auth0\Login\Contract\Auth0UserRepository as Auth0UserRepositoryContract;
use Auth0\Login\Repository\Auth0UserRepository as Auth0UserRepository;
And then your Register method should look like this:
public function register()
{
$this->app->bind( Auth0UserRepositoryContract::class, Auth0UserRepository::class );
$this->app->bind( Auth0UserRepositoryContract::class, Auth0UserRepository::class );
}
if you want to persist data in your database then Create your own Repository and update the bind method YourCustomerRepositoryContract::class, YourCustomerRepository::class
Just like that.
For more info about creating your own Repository
Auth0 PHP (Laravel) SDK Quickstarts: Login

What is the proper way to get ready a 3rd party package in Laravel 5 (5.4)?

I try to migrate an existing project from laravel 4 to laravel 5.
For that I installed a fresh laravel project and import code in it.
I installed a required package in laravel 5:
composer require jenssegers/agent
When I call Agent class to use, laravel gives following error:
Class 'App\Http\Controllers\Agent' not found
What is "use ..." line to add at the top of controller? Or any other solutions?
Not: use Agent; results in Class 'Agent' not found error
Since the Agent is a facade, you should use full namespace:
$agent = \Agent::....;
Or add use clause to the top of your controller:
use Agent;
You need to add facades in app/config/app.php
Laravel (optional)
Add the service provider in app/config/app.php:
'Jenssegers\Agent\AgentServiceProvider',
And add the Agent alias to app/config/app.php:
'Agent' => 'Jenssegers\Agent\Facades\Agent',
Source: https://github.com/jenssegers/agent

Dynamic redirect in package route

I have defined a route action with some business logic, inside an internally developed package. Depending on the result in this action, the app want to redirect the user to some dynamic route (Redirect::route('admin.index', [$app->id]) e.g).
How would I do this?
Any solution I come up with doesn't work because of the way Laravel handles routes.
Right now I have copied the route to the app routes.php, and extracted the business logic to a method inside the package. But this is not optimal, as I'd like to also keep the route inside the package.
Laravel has some documentation on Package Configuration that should work for you.
In your package's src/config/config.php:
<?php
return array(
'route_admin_index' => 'admin.index',
);
Change your package's code to:
Redirect::route(Config::get('your_package_name::route_admin_index'), [$app->id]);
Now when installed on different environments, you can do:
php artisan config:publish your_vendor_name/your_package_name
Which will publish your package's configuration file to:
app/config/packages/your_vendor_name/your_package_name
Where then you can change the route_admin_index at will.
If php artisan config:publish was not called. Your route will default back to what you have in your package's config file.

Why can't my class be found, when it's in the same namespace?

I have created a modules folder in my Laravel app. There are two modules so far, but I'm just concentrating on core here.
I'm using Confide and Entrust to build User functionality, like so:
namespace App\Modules\Core;
use Zizaco\Confide\ConfideUser;
use Zizaco\Entrust\HasRole;
class User extends ConfideUser {
use HasRole;
}
and Permissions:
namespace App\Modules\Core;
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
}
and Roles:
namespace App\Modules\Core;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
}
My Composer.json autoload reads:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/modules"
],
"psr-0": {
"App\\Modules\\": "modules/"
}
},
I put the psr-0 stuff in there because I couldn't get things to work. They still don't work, though the output autoload files when I run composer seem to have promising entries in them.
The database has been migrated, and now I'm trying to run the database seeding. My seeding script reads:
use App\Modules\Core\User;
use App\Modules\Core\Role;
use App\Modules\Core\Permission;
class UserTablesSeeder extends Seeder {
public function run()
{
DB::table('users')->insert(array(
'email' => 'xxx',
'first_name' => 'xxx',
'password' => 'xxxx',
'active' => 1
));
$admin = new Role;
$admin->name = 'Admin';
$admin->save();
$manageUsers = new Permission;
$manageUsers->name = 'manage_standard_users';
$manageUsers->display_name = 'Manage Users';
$manageUsers->save();
$admin->perms()->sync(array($manageUsers->id));
$user = User::where('email','=','xxx')->first();
$user->attachRole($admin);
}
}
But when I run php artisan db:seed I get an error:
PHP Fatal error: Class 'Permission' not found in /home/wedding/quincy/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 604
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'Permission' not found","file":"\/home\/wedding\/quincy\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Eloquent\/Model.php","line":604}}
If I get rid of all the namespacing it all works just fine, but I think I should keep the namespaces because of the modularity I'm trying to create.
I've run composer dump-autoload, and install for when I added the psr-0 entry. So I'm not sure what else I need to do. I'm very new to composer, so at this point I'm lost as to what the problem is.
Thanks in advance.
Don't know if you found your answer.
I think you need to update your role and permission namespaced class names here:
File: vendor/entrust/config/config.php:
(Default is just "Role" and "Permission" without a namespace, so it doesn't work when you move your implementations into one).
You also have two other options:
add an alias for the fully namedspaced permission and role class on the app/config.php (Role => "Namespace").
there's a mechanism to override package config settings with appropriately named files. You can override just the two entries you need (the Role and Permission namespaces).
Confide and Entrust both are looking for Role and Permission model in global namespace. As you have changed namespace of both these models, Confide and Entrust are not able to find it. To solve this problem, you need to override Entrust configuration.
Create directory "app/config/packages/zizaco/entrust"
Copy file "vendor/zizaco/entrust/src/config/config.php" to "app/config/packages/zizaco/entrust/config.php"
Edit "app/config/packages/zizaco/entrust/config.php" and change following two lines
'role' => 'App\Modules\Core\Role',
'permission' => 'App\Modules\Core\Permission',
php artisan clear-compiled
php artisan optimize
You should rely on Laravel's packages (created thru Workbench, for instance) while developing localy.
Packages are the primary way of adding functionality to Laravel.
Workbench packages and their classes are handled automaticaly by Laravel - no need to configure anything.
More informations here: http://laravel.com/docs/packages
if you want to use your own modules instead of standard workbench packages, check out this article that depics how to achieve that:
http://creolab.hr/2013/05/modules-in-laravel-4/
summary by the author ( Boris Strahija ):
Laravel 4 is heavily based on composer packages, which is a good thing, but sometimes developers (like myself) like to separate their code into modules. This is especially nice when building larger projects. Now this was fairly easy to do in Laravel 3 with the bundles system, but in Laravel 4 many people just recommend building packages since L4 has a nice workbench feature. This is all good, but sometimes I like to separate my app specific controllers and views into modules, and not have to go through it with the workbench.
In short, you have to
put your modules code somwhere (for example /app/modules/)
include the directory in composer.json file, under autoload/classmap
create an appropriate service providers (Laravel 4 uses service providers to register and boot up the packages, you can use it with modules as well)
register the service providers - add them to app config in “app/config/app.php” under the providers array
So now we have out modules fully working. You can add module specific routes, group your controllers/views/models, get module configuration like this:
Config::get('content::channels');
Or get translated phrases like this:
Lang::get('shop::errors.no_items_in_cart');
Finally, to test your modules you can create some routes, but that is up to you how you use your code.
If you look at Doctrine composer.json, for example /vendor/doctrine/cache/composer.json:
"autoload": {
"psr-0": { "Doctrine\\Common\\Cache\\": "lib/" }
},
The files are located in:
/vendor/doctrine/cache/lib/Doctrine/Common/Cache/ArrayCache.php
/vendor/doctrine/cache/lib/Doctrine/Common/Cache/Cache.php
... and so on
By that logic, I think you should put your files in:
modules/App/Modules/Core/User.php
modules/App/Modules/Core/Permission.php
modules/App/Modules/Core/Role.php
From you screenshot the Permission class is located in the models folder so when you include your namespace you should type
use App\Modules\Core\Models\Permission;

Resources