abkrim

CEO at Castris

Member Since 4 Years Ago

Pastrana

Experience Points
26,875
Total
Experience

3,125 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
218
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 6
26,875 XP
Mar
20
2 weeks ago
Activity icon

Replied to HasOne Not Show Anything

Oh my God...

Relation is belongsTo

Server resource

BelongsTo::make('Provider')->nullable(false)

Provider resource

public static $title = 'name';

Server model

public function provider()
{
    return $this->belongsTo(Provider::class);
}

Provider Model

public function server()
{
    return $this->hasMany('App\Server');
}

Thanks.

Activity icon

Replied to HasOne Not Show Anything

@bugsysha Yes is a mistake in typo... real is table server has a provider_id

Sever hasone Provider Provider hasmany Server

You can explian me? I'm lost and tried several ways and not work.

Activity icon

Started a new Conversation HasOne Not Show Anything

Laravel Nova 3.1.0 / Laravel 7.2.1

Models

Server

class Server extends Model
{
    use SoftDeletes, CascadeSoftDeletes;

    protected $guarded = [];


    public function provider()
    {
        return $this->hasOne('App\Provider');
    }

}

Provider

class Provider extends Model
{
    protected $guarded = [];

    public function server()
    {
        return $this->belongsTo('App\Server');
    }
}

Nova Resources

Server

public function fields(Request $request)
{
	return [
		ID::make()->sortable(),

		Text::make('FQDN')->sortable()->rules('required', 'max:255'),
		Text::make('alias')->sortable()->rules('max:255'),

		HasOne::make('Proveedor', 'provider', 'App\Nova\Provider')

		// Try also 
		// 	HasOne::make('Provider')
	];
}

Provider

public function fields(Request $request)
{
	return [
		ID::make()->sortable(),

		Text::make('Nombre', 'name')->sortable()->rules('required', 'max:100'),
		Text::make('Teléfono','telephone')->rules('max:20'),
		Textarea::make('Notas','notes')->alwaysShow(),
	];
}
  • On table Provider has two providers.
  • Table providers has a provider_id column.

I don't see my mistake ... I've been head butting all morning

Feb
13
1 month ago
Activity icon

Replied to Translation Nova Cards

Oh my God... very hard a doc os Laravel Nova.

Solution is more simple

<p class="text-90 leading-normal">
    {{ __('Card1') }}
</p>
Activity icon

Started a new Conversation Translation Nova Cards

I needs make translatable my cards. But I don't see in manual how to I can made this.

Your Nova card's service provider registers your card's compiled assets so that they will be available to the Nova front-end:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    $this->app->booted(function () {
        $this->routes();
    });

    Nova::serving(function (ServingNova $event) {
        Nova::script('{{ component }}', __DIR__.'/../dist/js/card.js');
        Nova::style('{{ component }}', __DIR__.'/../dist/css/card.css');
        Nova::translations(__DIR__.'/../resources/lang/en/card.json');
    });
}

Well.

I create un my Card translations tests

nova-components/mycard/resources/lang/es/card.json (and /en)

{
    "Card1": "This is an example in English"
}

nova-components/mycard/resources/js/components/Card.vue

Below get error in console

...
<p class="text-90 leading-normal">
    {{ $t('Card1') }}
</p>

Also I tried, but this saws original text

<p class="text-90 leading-normal">
    __('Card1')
</p>

This usually for me for use in my vue projets (not mixin Laravel & Vue. Full vue)

But not work, because $t is not defined.

I'm lost with documentation.

Activity icon

Replied to Translation Of BelongsTo In Nova

Solution is in doc. It needs 3 parameters, label, table and model.

HasMany::make(__('Mailboxes'), 'mailboxes', Mailbox::class)
Activity icon

Replied to Nova Field Validate Using Data Of Other Field

Well.

I read this. But I don't understand how to I send to rule data for verify if $attribute has a $value and this $value has part of other attribute named "domain"

According documentation object rules

 public function passes($attribute, $value)
    {
        return strtoupper($value) === $value;
    }

On your reply I don't see a way for pass data to rule. Data (And my question) is field on relationship BelongTo, named "domain"

Best regards

Feb
12
1 month ago
Activity icon

Started a new Conversation Nova Field Validate Using Data Of Other Field

Hi.

I have a text field (email) that needs to be validated with the value of a BelongsTo relationship

Text::make(__('Mailbox'), 'username')
    ->sortable()
    ->rules('required', 'email', 'max:254')
    ->creationRules('unique:mailboxes,username')
    ->readonly(function() {
        return $this->resource->id ? true : false;
    }),
...
BelongsTo::make('Domain')->hideFromDetail()->hideWhenUpdating(),

I need that user validate a mailbox with a valid email of same domain selected in BelongsTo.

Is possible ?

Feb
10
1 month ago
Activity icon

Replied to Translation Of BelongsTo In Nova

I forget put this solution on my post.

This solution not work because Nova try to with with Model translation... App\Nova\Usuario instead correct class App\Nova\User

[2020-02-10 19:56:35] local.ERROR: Class 'App\Nova\Usuario' not found {"userId":1,"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Class 'App\Nova\Usuario' not found at /home/abkrim/Sites/albaridnova/vendor/laravel/nova/src/Fields/BelongsTo.php:118)

Activity icon

Started a new Conversation Translation Of BelongsTo In Nova

I use for translations fields in Nova

Text::make(__('Name User'), 'name')

But I don't understand the manual to make the title of the BelongsTo fields translatable

Title Attributes When a BelongsTo field is shown on a resource creation / update screen, a drop-down selection menu or search menu will display the "title" of the resource. For example, a User resource may use the name attribute as its title. Then, when the resource is shown in a BelongsTo selection menu, that attribute will be displayed:

Well... On my code

BelongsTo::make('User')->withMeta([
  'belongsToId' =>  $this->user_id ?? auth()->user()->id
])->hideFromDetail()

Code on Nova\User

public static $model = 'App\User';

public static $title = 'email';

public static $search = ['id', 'name', 'email'];

public static function availableForNavigation(Request $request)
{
    return $request->user()->isAdmin();
}

public static function label()
{
    return __('Users');
}

public static function singularLabel()
{
    return __('User');
}

When show User resource not problem. Labels translations are done.

But if go to resource Mailbox, field BelongsTo not show translations

Activity icon

Replied to Text Field With Asterisk But Not Password

Sorry, but post is in Nova section. Now I edit the content so that it is better understood.

Activity icon

Started a new Conversation Text Field With Asterisk But Not Password

I need to use in Laravel NOVA a Text field but with same model of password.

I like that data input by user convert it's showed with asterisks.

it's possible?

Feb
08
2 months ago
Activity icon

Replied to Issues When Use A Model Without Id

A lot of thanks for your effort. After this problems, I get way for add id to tables without id, and refactor app and mother app. Is more easy for me.

Best regards.

Activity icon

Replied to Issues When Use A Model Without Id

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDomainsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('domains', function (Blueprint $table) {
            $table->string('domain')->unique();
            $table->unsignedInteger('user_id')->nullable(false)
                ->comment('Albarid for best performance with relations tables');
            $table->text('description')->nullable();
            $table->text('disclaimer')->nullable();
            $table->unsignedInteger('aliases')->nullable(false)->default(0);
            $table->unsignedInteger('mailboxes')->nullable(false)->default(0);
            $table->unsignedInteger('maillists')->nullable(false)->default(0);
            $table->unsignedInteger('quota')->nullable(false)->default(0)->comment('Real quota asigned in Mb');
            $table->unsignedInteger('max_quota')->nullable(false)->default(0)->comment('Grace quota asigned in Mb');
            $table->unsignedBigInteger('quota_used')->nullable(false)->default(0)->comment('Quota used in Bytes');
            $table->unsignedInteger('quota_user_default')->nullable(false)->default(1024)
                ->comment('QUota default mailbox in Megabytes');
            $table->string('transport')->nullable(false)->default('dovecot');
            $table->boolean('backupmx')->nullable(false)->default(false)->index();
            // $table->json('settings')->nullable();
            $table->boolean('active')->nullable(false)->default(true)->index();
            $table->timestamps();
            $table->softDeletes();
            $table->timestamp('expires_in')->nullable(true)->index();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('domains');
    }
}

Activity icon

Started a new Conversation Issues When Use A Model Without Id

I use a model without id for compatiblity of software

class Domain extends Model
{
    use SoftDeletes, CascadeSoftDeletes;

    protected $cascadeDeletes = ['mailboxes'];

    protected $primaryKey = 'domain';

    protected $keyType = 'string';

    public $incrementing = false;

When try use with delete, softdelete , get error

[previous exception] [object] (PDOException(code: 22007): SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'villegas.net' for column `albaridnova`.`action_events`.`actionable_id` at row 1 at /home/abkrim/Sites/albaridnova/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:121)
[stacktrace]

Any body know issues for this question?

Jan
13
2 months ago
Activity icon

Replied to Complete Nova Serie With Minimal Chapter About How To Test With Nova

Calling someone who speaks to you with education, and who can be your father, is an unequivocal sign of your bad education. But I guess it's normal for some young people today.

Activity icon

Replied to Complete Nova Serie With Minimal Chapter About How To Test With Nova

Ok, have a good day. Appreciated your interest in the opinion, but here I stopped reading.

Jan
12
2 months ago
Activity icon

Replied to Complete Nova Serie With Minimal Chapter About How To Test With Nova

Dusk is a system to test the application in browser mode. There are many tests that do not need the heavy Dusk, such as policies, permissions, or other questions.

Dusk for the tests is fine, the integration with browser, but not for that type of tests. So it's not about doing tests to do them. Laravel Nova gives you a series of things, but it is not a finished construction, but you must finish and therefore have many tests to perform.

And these types of tests, which are super easy when we test our api, or a normal application of Laravel, are no longer so much in Laravel Nova.

Best regards.

Jan
10
2 months ago
Activity icon

Replied to Testing Nova

@manelgavalda oops, sorry for mistake. I forget put error. I've updated post

Activity icon

Started a new Conversation Testing Nova

I like test my dashboard app made with nova.

I'm looking form examples in internet, but only see a example for use Spatie\Permission but I don't need this package.

My test code fail

/** @test */
    function super_admin_has_ui_access()
    {
        $user = factory(User::class)->create(['is_super_admin' => true]);

        $response = $this->actingAs($user)
            ->get('/nova/resources/users/1');


        $response->assertStatus(200);
    }

Also if test only dashdoard

$response = $this->actingAs($user)
            ->withSession(['foo' => 'bar'])
            ->get('/nova/dashboards/main');

error

1) Tests\Feature\NovaAccessTest::super_admin_has_ui_access
Expected status code 200 but received 403.
Failed asserting that false is true.

/home/abkrim/Sites/albarid/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:185
/home/abkrim/Sites/albarid/tests/Feature/NovaAccessTest.php:20

Any ideas?

Activity icon

Started a new Conversation Complete Nova Serie With Minimal Chapter About How To Test With Nova

Hi.

I think it would be very good for the community, one more chapter of Nova, in which the issue of testing with Nova will be addressed, which does not have much doc or many articles published on the network.

Activity icon

Replied to Nova IndexQuery In Relationships Of Relationship

Well.

After some works and searches, I see that problem is Nova not support "Has Many Through" relations. For me best solution, is add relation between table on third level with first level. I think is athe best workaorund about this issue.

Laravel Nova relations supported:

  • HasOne
  • HasMany
  • BelongsTo
  • BelongsToMany
  • MorphOne
  • MorphMany
  • MorphTo
  • MorphToMany
  • Searchable Relations

And conversation in github about problem...

Jan
08
3 months ago
Activity icon

Replied to Nova IndexQuery In Relationships Of Relationship

You reply is same that my code.... but you using model class instead 'App\Model' @bugsysha and also in your code you delete parameters that app need for relations, because models relation is 'domain' not 'id'.

This

return $this->hasMany(Mailbox::class, 'domain', 'domain');

Is same below

return $this->hasMany('App\Mailbox', 'domain', 'domain');
Activity icon

Started a new Conversation Nova IndexQuery In Relationships Of Relationship

I've 3 models

User has a hasmany relation (domains()) with Domain and this hasMany relation (mailboxes) with Mailbox

User.php

public function domains()
{
    return $this->hasMany(Domain::class);
}

Domain.php

public function user()
{
    return $this->belongsTo(User::class);
}

public function mailboxes()
{
    return $this->hasMany(Mailbox::class, 'domain', 'domain');
}

Mailbox.php

public function domains()
{
    return $this->belongsTo('App\Domain', 'domain', 'domain');
}

Code below work fine for get only mailboxes owned but if put in policies not work.

public function view(User $user, Mailbox $mailbox)
{
    $domains = Domain::where('user_id', $user->id)->pluck('domain')->toArray();

    return User::with([
        'domains.mailboxes' => function ($builder) use ($domains) {
            $builder->where('domain',$domains);
        }
    ])->find($user);

}

I tried overrinding indexQuery on my Nova/Mailbox model, but not work. Retunr all mailboxes on database

public static function indexQuery(NovaRequest $request, $query)
{

    $domains = Domain::where('user_id', $request->user()->id)->pluck('domain')->toArray();

    return User::with([
        'domains.mailboxes' => function ($builder) use ($domains) {
            $builder->where('domain',$domains);
        }
    ])->find($user);

    if ($request->user()->is_super_admin) {
        return $query;
    } else {
        return User::with([
            'domains.mailboxes' => function ($builder) use ($domains) {
                $builder->where('domain',$domains);
            }
        ])->find($user);
    }
}

On tinker (thanks to @tykus on post https://laracasts.com/discuss/channels/eloquent/understanding-eager-loading-with-lineal-relationship) workfine, but on Nova, user see all mailbox.

Also if activate MailboxesPolicy in AuthServiceProvider, user only index all mailboxes, but can not edit or delete.

Activity icon

Replied to Understanding Eager Loading With Lineal Relationship

Sorry for my understanding..

/* mailboxes owned of user for use in mi Policies *

On tinker a tried..

User::with(['domains.mailboxes' => function ($builder) { $builder->where(); } ])->find(2)
TypeError: Too few arguments to function Illuminate/Database/Eloquent/Builder::where(), 0 passed in /home/abkrim/Sites/albarid/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php on line 23 and at least 1 expected

 Too few arguments to function Illuminate\Database\Eloquent\Builder::where(), 0 passed in /home/abkrim/albarid/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php on line 23 and at least 1 expected {"userId":2,"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Too few arguments to function Illuminate\Database\Eloquent\Builder::where(), 0 passed in /home/abkrim/albarid/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php on line 23 and at least 1 expected at /home/abkrim/albarid/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:225)

With my level I do not reach what you want to explain to me: very grateful anyway, @tykus

Tried on my policies but not work

public function view(User $user, Mailbox $mailbox)
    {
        $domains = Domain::where('user_id', $user->id)->pluck('domain')->toArray();

        return User::with([
            'domains.mailboxes' => function ($builder) use ($domains) {
                $builder->where('domain',$domains);
            }
        ])->find($user);

    }
Activity icon

Started a new Conversation Understanding Eager Loading With Lineal Relationship

Hi.

I have three models

User has a hasmany relation (domains()) with Domain and this hasMany relation (mailboxes) with Mailbox

User.php

public function domains()
{
    return $this->hasMany(Domain::class);
}

Domain.php

public function user()
{
    return $this->belongsTo(User::class);
}

public function mailboxes()
{
    return $this->hasMany(Mailbox::class, 'domain', 'domain');
}

Mailbox.php

public function domains()
{
    return $this->belongsTo('App\Domain', 'domain', 'domain');
}

I need create a query for return only mailboxes owned of user for use in mi Policies.

I tried User::find($user)->with('domains.mailboxes')->get() but is not correct.

Any ideas?

Jan
07
3 months ago
Activity icon

Replied to PasswordConfirmation With Translations Not Work Validation

A lot of thanks... Mistake. I re-read doc now. Thanks. @bugsysha

Activity icon

Replied to PasswordConfirmation With Translations Not Work Validation

If user change password and not put anything in input Password Confirmation, app save or update data, instead stop and show error of validation.

Jan
06
3 months ago
Activity icon

Started a new Conversation PasswordConfirmation With Translations Not Work Validation

My app uses translations.

I use latest laravel nova 2.X and laravel 6.X

When try use translations, validations not check if user confirm password or if this is wrong. Save form without confirmation.

Password::make(__('Password'), 'password')
    ->onlyOnForms()
    ->creationRules('required', 'string', 'min:8')
    ->updateRules('nullable', 'string', 'min:8'),

PasswordConfirmation::make(__('Password Confirmation'), 'password_confirmation')
->onlyOnForms(),

Any mistake on code?

Dec
19
3 months ago
Activity icon

Replied to [SOLVED] Upgrade System To PHP 7.4 Fail Only Test For Users

In my tests I had not taken into account the page, and I placed a line in TestCase in which to capture the tests, a factory of 25 users was made.

By eliminating it, I corrected the problem and then checked that in php 74 everything worked fine.

It is what makes me fall in love with the tests.

Activity icon

Replied to [SOLVED] Upgrade System To PHP 7.4 Fail Only Test For Users

Mistake is TestCase setUp() method add a seeder of Users.. a line add a factory user with 25 items.

Activity icon

Replied to [SOLVED] Upgrade System To PHP 7.4 Fail Only Test For Users

I did not like your answer, since there is no problem in it. The construct inherits from the father, and it is necessary to me since the assigned value is not fixed in the model, but in the configuration.

In any case, delete the constructor, and limit me to setting the fixed value using its method, and the result is the same.

1) Tests\Feature\Users\UserFeaturesTest::a_super_admin_can_get_index_users
Failed to assert that the response count matched the expected 15
Failed asserting that actual size 43 matches expected size 15.

Once again, when entering the limit, the test fails, and the tes uses mysql instead of sqlite in memory.

Seen this I will open a PR since I think it is a bug,

Thanks for your time.

Activity icon

Replied to [SOLVED] Upgrade System To PHP 7.4 Fail Only Test For Users

Oh my good...

Just I see a problem and don't understand.

Just added on User model a same code for user pagination (used in Domains and Mailoboxes)

public function __construct(array $attributes = array())
    {
        parent::__construct($attributes);

        $this->perPage = config('albarid.pagination');
    }

Well. If delete this piece of code, work fine.

I don't understand. I'm using this code in all my models and work fine.

Activity icon

Replied to [SOLVED] Upgrade System To PHP 7.4 Fail Only Test For Users

In phpunit.xml

<server name="APP_ENV" value="testing"/>
<server name="DB_CONNECTION" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>

database.php

'testing' => [
            'driver' => 'sqlite',
            'database' => ':memory:',
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],
Activity icon

Replied to [SOLVED] Upgrade System To PHP 7.4 Fail Only Test For Users

Are working for last 6 months, using sqlite in memory

On TestCase using

use CreatesApplication, DatabaseMigrations, DatabaseTransactions;

And 25 files of test for Domains, and Mailboxes, working with same configuration. An this test, running several factories without problem.

Only fail Users tests.

Well, now after make changes and reboot machine. error is for all

vendor/bin/phpunit                                                                                                                                                                                

In DatabaseManager.php line 152:
                                     
  Database [sqlite] not configured.                                       

 a tinker                                                                                                                                                                              ✔  
>>> config('database.connections')
=> [
     "mysql" => [
       "driver" => "mysql",
       "url" => null,
       "host" => "192.168.1.40",
       "port" => "3306",
       "database" => "albarid",
       "username" => "albarid",
       "password" => "wdYnvN88y5YvhYREh9VP",
       "unix_socket" => "",
       "charset" => "utf8mb4",
       "collation" => "utf8mb4_unicode_ci",
       "prefix" => "",
       "prefix_indexes" => true,
       "strict" => true,
       "engine" => null,
       "options" => [],
     ],
     "testing" => [
       "driver" => "sqlite",
       "database" => ":memory:",
       "prefix" => "",
       "foreign_key_constraints" => true,
     ],
   ]

Just unisntall php 7.4 and come back to php 7.3, restores all files from last ngith backup and all test work fine.

PHPUnit 8.5.0 by Sebastian Bergmann and contributors.

................................................................. 65 / 77 ( 84%)
............                                                      77 / 77 (100%)

Time: 12 seconds, Memory: 44.00 MB

OK (77 tests, 159 assertions)

Activity icon

Started a new Conversation [SOLVED] Upgrade System To PHP 7.4 Fail Only Test For Users

Hi.

I'm desesperate.

Today upgrade my develop system to PHP 7.4. Well after upgrade, run test and I see fails on Users tests.

  1. I run test by folder (models) Domain, Mailboxes. All work fine
  2. Run test for users, and I get error.

Error?

Only user nas a problem, and there're using mysql database, instead sqlite in memory.

A simple test for verify problem

function a_super_admin_can_get_index_users()
    {
        Passport::actingAs(
            factory(User::class)->create(['is_super_admin' => true])
        );

        // factory(User::class, 15)->create();

        $response = $this->get('/api/v1/users');

        dd($response);  // For verify problem

        $response
            ->assertStatus(200)
            ->assertJsonCount(15, $key = 'data');
    }

Response show 28 users there're in Mysql database. Buty my test using sqlite.

Desesperate

Nov
25
4 months ago
Activity icon

Started a new Conversation Policies Differents For The Owner User Or For The Admin

There is something I do not understand about policies

I have an API in which I have a user and another table. A user can only do certain things, and certain things only with certain elements.

Now when I want to refactor my controllers, I have realized that I am not aware of the knowledge of the policies.

For example

In my controller, an user can't edit some columns of his domain. Only admin has permission for edit this columns.

// Check params not allowed
        $check = ['aliases', 'mailboxes', 'maillists', 'quota_used', 'transport', 'backupmx'];
        if (! Auth::user()->is_super_admin) {
            $check = array_merge($check, ['settings', 'disclaimer', 'maxquota']);
        }

        if (!$this->checkParams($check, $request)) {
            return  $this->sendError(
                'There is content that is allowed to use in this method ' . $request->domain,
                [],
                Response::HTTP_PRECONDITION_FAILED
            );
        };

....

public function checkParams(array $added, Request $request): bool
    {
        // Check for no valid updates
        $not_update = array_merge($added, config('albarid.not_update'));

        if (!empty(array_intersect($not_update, array_keys($request->all())))) {
            return false;
        };

        return true;
    }

Is possible use Policies for control what cand edit or store user ?

Nov
07
5 months ago
Activity icon

Replied to Factories With Closure

Best result for me is below, but I think, that there're a best way.

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => bcrypt('12345'), // password
        'remember_token' => Str::random(10),
        'is_super_admin' => false,
        'scope' => json_encode([])
    ];
});

$factory->afterCreating(User::class, function ($user, $faker) {
    $scope = [];

    for ($i = 1; $i <= random_int(1,5); $i++) {
        $domain = new Domain;
        $domain->domain = $faker->unique()->domainName;
        $domain->settings = 'default_user_quota:1024';
        $domain->albarid_settings = json_encode(['default_user_quota' => 1024]);
        $domain->created = '2019-08-27 16:28:01';
        $domain->save();

        $scope[] = $domain->domain;
    }
    // Save scope to user
    $user->scope = json_encode($scope);
    $user->save();
});
Activity icon

Replied to Factories With Closure

Work fine, In my works try this options before..

dd(json_encode($scope));
"["morissette.com","bogisich.biz","dickens.com","okeefe.org","pfeffer.net","jakubowski.com","dare.com"]"

Also verify that 7 domains are in table.

But if verify code, in tinker or in code, dd(), return a closure instead json.

Closure() {#912
  class: "Illuminate\Database\Eloquent\Factory"
  this: Illuminate\Database\Eloquent\Factory {#917 …}
  file: "./database/factories/UserFactory.php"
  line: "20 to 28"
}
Activity icon

Replied to Factories With Closure

Thanks.

@sinnbeck for the tip, now almost in table domain has faker domains.

But in 'scope' row has not works.

All values for are a empty json {}

I put a echo for see closure and work fine,

USerTableSeeder

factory(App\Models\Albarid\User::class, 25)->create();

USerFactory

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => bcrypt('12345'), // password
        'remember_token' => Str::random(10),
        'is_super_admin' => false,
        'scope' => function () {
            $scope = [];
            $domains = factory(App\Models\Vmail\Domain::class,random_int(2,10))->create();
            foreach ($domains as $domain) {
                // echo 'Domain: '.$domain->domain.PHP_EOL;
                $scope[] = $domain->domain;
            }
            return json_encode($scope);
        }
    ];
});

@schez1983 scope is a json column, that it's muts contain domains of users such:

["gulgowski.com","kub.info","lubowitz.biz","mckenzie.com","cassin.biz","yundt.com","swaniawski.info"]
Activity icon

Started a new Conversation Factories With Closure

I am trying to create a factory but I don't achieve my goal.

I need to create users that have a field, scope, that requires creating elements in another table (domains)

These tables do not work with the Laravel model, so I cannot make relationships between them.

  • each user has at least one domain
  • in row scope all domains must in json format
  • a domain can only be one user
$factory->define(App\Models\Albarid\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => bcrypt('password'), // password
        'remember_token' => Str::random(10),
        'is_super_admin' => false,
        'scope' => json_encode(function () {
            $scope = [];
            $domains = factory(App\Models\Vmail\Domain::class,random_int(2,10))->create();
            foreach ($domains as $domain) {
                $scope[] = $domain->domain;
            }
            return $scope;
        })
    ];
});

DomainFactory

$factory->define(App\Models\Vmail\Domain::class, function (Faker $faker) {
    return [
        'domain' => $faker->unique()->domainName,
        'settings' => 'default_user_quota:1024',
        'albarid_settings' => json_encode( ['default_user_quota' => 1024]),
    ];
});

I know that I have a problem understanding how to work with factories but I can't get it done

Oct
17
5 months ago
Activity icon

Replied to Passport API: Understanding How It Works

A lot fo thanks. Sorry for delay.