Go through an array of a model (laravel)

0

I have a class Roles where I define a static array like this

<?php

namespace App;

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{

    public static $roles = [
        'admin1aaa' => [
            'name' => 'admin2aaa',
            'display_name' => 'Usuario admin',
            ] ,
        'secretary' => [
            'name' => 'secretary',
            'display_name' => 'Usuario de secretaria',
        ],
        'teacher' => [
            'name' => 'teacher',
        ]
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','display_name','description'
    ];

    /**
     * Get all users a role belongs to.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users()
    {
        return $this->belongsToMany('App\User')->withTimestamps();
    }
}

What I'm trying to do is check if the elements of the array of roles that are in Role::$roles but the elements in the table that insert them exist, the problem that I have that both Role::$roles as Role::all() I have the feeling that will find the array of the model, and what I need is that in one case it does the array of the model and in the other case it does so from the table of the data base .. but I do not see how to do it

public function createRoles()
    {
        $countDone =0;
        $countFail =0;

        foreach (Role::$roles as $key => $value) {

            $role = Role::all()->find('name',$value['name']);

            if ($role === null) {

                $owner = new Role();
                $owner->name = $value['name'];
                $owner->display_name = $value['display_name'];

                if ($owner->save())
                    $countDone++;
                else
                    $countFail++;
            }
        }


        return $this->jsonCreatedResponse('Roles created correctly : '.$countDone . ' Failed : '. $countFail);
    }
    
asked by ilernet 07.08.2018 в 14:40
source

1 answer

0

Hi, first of all, I think you should give the following form to your $roles :

<?php

namespace App;

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{

    public static $roles = [
            'admin'     => [
                ['name' => 'admin', 'display_name' => 'Usuario admin'],
            ],
            'secretary' => [
                ['name' => 'secretary', 'display_name' => 'Usuario de secretaria'],
            ]
        ];

Then, you can do the following.

    // mapeando arreglo
    $roles_to_check = collect(Role::$roles)->flatten(1);
    // obteniendo roles existentes
    $roles_existentes = Role::whereIn('name', $roles_to_check->pluck('name'))
        ->get()
        ->map(function ($role) {
            return [
                'name'         => $role->name,
                'display_name' => $role->display_name,
            ];
        });
    // creando arreglo de nuevos roles
    $roles_to_add = $roles_to_check->whereNotIn('name', $roles_existentes->pluck('name'));
    // creando nuevos roles
    $roles_to_add->each(function ($newRole) {
        $owner = Role::create([
                'name'         => $newRole['name'],
                'display_name' => $newRole['display_name'],
            ]);
    });

    return $this->jsonCreatedResponse('Roles created correctly: ' . $roles_to_add->count());

Basically what this code does is avoid recurring queries to the database to know if the role exists or not (as you were doing in your foreach ), to achieve this:

  • I get the existing roles
  • I compare all the elements of your arrangement with the existing ones in the database to know the new ones to add.
  • I add the elements.
  • PS: The comments made to you are correct, you should be more specific when making your inquiries. It has taken me a long time to decipher what you are trying to do (and that I am still not sure what I have assumed).

        
    answered by 07.08.2018 в 16:27