Only one seed not working Laravel 5.5 - laravel-5

all seeds are working but one throws exception
Call to undefined method Illuminate\Support\Facades\Lang::setContainer()
public function run()
{
DB::table('lang')->insert([
[
'lang_name' => 'Русский'
],
[
'lang_name' => 'English'
],
[
'lang_name' => 'Empty'
]
]);
}

can you try changing the Seeder class name to something else? Like LangSeeder ? And not Lang?
Looks like Lang is a class name used by Laravel already and seeder classes are in root namespace!

Related

Migration - How to set default value for json? (MySQL)

I have the problem that I need some values to be already set for my settings json column.
Let us say I have this in my user migration file:
$table->json('settings');
My goal is to set let us say these values as default:
'settings' => json_encode([
'mail' => [
'hasNewsletter' => false
],
'time' => [
'timezone' => ''
]
])
How would you do this?
My first approach was to set the values in my UserObserver in the created event after the User was created.
This creates the problem, that my UserFactory is not working correctly. Because a User is created but the settings values are overwritten by the UserObserver again...
Following solution works with Eloquent Model.
For default JSON data you can do something like this in your Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $attributes = [
'settings' => '{
"mail": {
"hasNewsletter" : false
},
"time": {
"timezone" : ""
}
}'
];
}
Then the default value will be {"mail": {"hasNewsletter" : false},"time": {"timezone" :""} in your DB if your input is null. However the existing values in DB will be unchanged and will have to change manually if you need.
If you want to keep your existing DB values null (and/or when null) but want to get as the above default json by Eloquent, you can add the following method in the Model:
protected function castAttribute($key, $value)
{
if ($this->getCastType($key) == 'array' && is_null($value)) {
return '{
"mail":{
"hasNewsletter":false
},
"time":{
"timezone":""
}
}';
}
return parent::castAttribute($key, $value);
}
Note: above castAttribute method will return this same json/data for all null json column of your model. It's better to set empty array here.
Tested in Laravel 5.8.
Reference: https://laravel.com/docs/eloquent#default-attribute-values

How to mock authentication user on unit tests with Codeception in Laravel 5?

I have to convert my unit tests to codeception. I need to use loginWithFakeUser() function from this article - How to mock authentication user on unit test in Laravel?
public function loginWithFakeUser() {
$user = new User([
'id' => 1,
'name' => 'yish'
]);
$this->be($user);
}
How can I use the $this->be() when my class is already extending \Codeception\Test\Unit? I don't know what should I use .. or how to use properly. Putting the function loginWithFakeUser() inside this:
use Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication;
use Illuminate\Foundation\Testing\Concerns\InteractsWithSession;
class AdminTest extends \Codeception\Test\Unit {
use InteractsWithAuthentication;
use InteractsWithSession;
}
Gives me an error:
[ErrorException] Undefined property: AdminTest::$app
I'm not sure how can I set the $app variable. Please help me. Thanks a lot!
I was able to solve this by mocking the Auth class.
$oUser = new User([
'id' => 1,
'name' => 'yish'
]);
Auth::shouldReceive('check')->once()->andReturn(true);
Auth::shouldReceive('user')->once()->andReturn($oUser);
Where in my actual code it uses it as:
if(Auth::check() === true) {
$sName = Auth::user()->name;
}

How do I configure a custom form element with zend expressive

In my ZF2 Application, I had several custom form Elements with an injected database Adapter. I put the configuration in the module.php file with a method, like this:
public function getFormElementConfig()
{
return array(
'factories' => [
'dksCodeElementSelect' => function($container)
{
$db = $container->get(AdapterInterface::class);
$elemnt = new Form\Element\Select\DksCodeElementSelect();
$elemnt->setDb($db);
return $elemnt;
},
)
}
How can I configure custom form elements within a zend-expressive application?
Form class calls elements via 'FormElementManger'. and FormElementManager reads 'form_elements' key from config. It's basicly a container (service manager) so you have to configure it same as container (factories, invokables, aliases etc). Also, you have to register Zend/Form module to container. I didn't try it but has to be ths way;
(ps: it's too late here, if it doesn't work let me know so i can put a working example.)
class MyModule\ConfigProvider {
public function __invoke()
{
return [
'dependencies' => $this->getDependencies(),
'templates' => $this->getTemplates(),
'form_elements => [
/* this is where you will put configuration */
'factories' => [
MyElement::class => MyElementFactory::class,
]
]
];
}
}

Auth::attempt() in laravel 4.2 proper usage

im trying to use Auth::attempt($credentials) in my controller and here is my sample code
$credentials= [
'SystemUserName' => Input::get('username'),
'SystemUserPassword' => Input::get('password')
];
then im having a error saying Undefined Index: Password only to know that i can use any field for username but i can't do that for the password because it should be 'password'. the thing is SystemUserName and SystemUserPassword are column names in my database. How can i do this properly? any ideas?
Unfortunately you can use only the 'password' column name with the included database and eloquent drivers, because the column name is hardcoded in the user provider. So your only bet is to create your own custom driver by extending the Eloquent one. This can be done in four easy steps as explained below:
1. Create your custom driver class file in app/extensions/CustomUserProvider.php file with the following contents:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Auth\UserProviderInterface;
class MyCustomUserProvider extends EloquentUserProvider implements UserProviderInterface {
public function retrieveByCredentials(array $credentials)
{
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if ($key != 'SystemUserPassword') $query->where($key, $value);
}
return $query->first();
}
public function validateCredentials(UserInterface $user, array $credentials)
{
return $this->hasher->check($credentials['SystemUserPassword'], $user->SystemUserPassword);
}
}
2. Add "app/extensions" to your composer.json in the classmap section:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/extensions" // <-- add this line here
]
},
Then run a php composer dump-autoload.
3. In your app/start/global.php file add this to register your custom driver:
Auth::extend('mydriver', function($app)
{
return new MyCustomUserProvider($app['hash'], Config::get('auth.model'));
});
4. Then just set the driver in your app/config/auth.php to this:
'driver' => 'mydriver',
This was tested and it works just fine.
Mind you, this will work assuming your user passwords were hashed with the Hash::make() method Laravel offers and stored that way in the database. If not, then you need to adjust the validateCredentials method in MyCustomUserProvider with your own compare method between the plain and hashed password.

How to use URL:: or asset() in config files in laravel 5

In any config file If I use URL class I get the error 'Class URL not found'; if I use the function "asset", when I update composer.json I get this error:
Catchable fatal error: Argument 2 passed to Illuminate\Routing\UrlGenerator::__construct() must be an instance of Illuminate\Http\Request, null given,
Outside of config files both work fine
return [
'photos_url' => URL::asset('xxx'),
];
or
return [
'photos_url' => asset('xxx'),
];
Test
echo config('site.photos_url'); // or echo Config::get('site.photos_url');
Configs are loaded really early and probably not meant to use anything from the framework except Dotenv
return [
'photos_url' => URL::asset('xxx'),
];
Instead you can use:
return [
'photos_url' => env('APP_URL').'/rest_of_path.ext',
];
Source: Laravel Issue #7671
You shouldn't use dynamic code in your config. As a solution you can use ConfigServiceProvider to add any specific cases:
public function register()
{
config([
'photos_url' => assets('xxx'),
'services.facebook.redirect' => url('auth/callback/facebook'),
]);
}
Source: https://github.com/laravel/framework/issues/7671

Resources