ravasaurio

Experience

4,740

0 Best Reply Awards

  • Member Since 1 Year Ago
  • 40 Lessons Completed
  • 0 Favorites

11th October, 2018

ravasaurio left a reply on Page Freezes When Redirected After Sending Big Task To The Background. • 5 days ago

@ohffs do you think that might be the problem? sounds strange to me, because even if I use the big CSV, the job starts and I get redirected correctly by that last line on the controller. But then the page freezes, even with the job running and ultimately finishing successfully.

ravasaurio started a new conversation Page Freezes When Redirected After Sending Big Task To The Background. • 5 days ago

I have a form for uploading a CSV file and import its users to my database. When I hit the import button, I perform some validation, get the data from the CSV into an array, and I dispatch a job that imports the users with a foreach loop in the background.

I have tested this with a 10 users CSV and it works great. However, when I use a 1000 users CSV, when I dispatch the job and redirect, the page I get redirected to freezes. The job keeps running in the background and it imports the 1000 users succesfully. But even when it finishes running, the page won't unfreeze, to the point that Chrome shows me the "This page is'nt working" message and offers me to close it or wait.

The app itself doesn't freeze, if I have another tab opened, it will work perfectly, and works great with another computer too (this isn't strange as the server is a remote one). Just the page that sends the file with the form gets freezed.

Here's the code:

public function store(CsvImportRequest $request)
    {
      $rows = $this->userImportRepository->csvToArray($request->file('users-file'));
      if($rows instanceof \Illuminate\Http\RedirectResponse) {
        return $rows;
      }

      $this->userImportRepository->validateData($rows);

      $this->userImportRepository->storeImportUsers($rows,$request->master);

      return redirect()->route('admin.dashboard')->withFlashSuccess('Alta masiva en curso.');
    }

csvToArray:

public function csvToArray($file)
  {
    $data = array();

    $csvData = file_get_contents($file);

    $rows = array_map(function($v){return str_getcsv($v, '|');}, file($file)); // delimiter-> |
    //$rows = array_map('str_getcsv', explode("\n", $csvData)); // delimiter-> ,

    $header = array_shift($rows);

    $i = 1;
    foreach($rows as $row) {
      $i++;
      if(count($header) == count($row)){
        array_push($data, array_combine($header,$row));
      } else {
        return redirect()->route('admin.import.index')->withFlashDanger('Error en la linea '. $i .': Faltan datos. Comprueba que todos los | están presentes.');
      }
    }

    $data = $this->array_trim($data);

    return $data;
  }

validateData:

  public function validateData($rows)
  {
    $validator = Validator::make($rows, [
      '*.first_name'    =>  'required',
      '*.last_name'     =>  'required',
      '*.email'         =>  'required|email|unique:users',
      '*.assigned_test' =>  'nullable|numeric|exists:tests,id',
    ])->validate();
  }

storeImportUsers:

public function storeImportUsers($rows,$master)
  {
    $userRepository = new UserRepository;
    $master= Master::find($master);

    BulkImportUsers::dispatch($rows,$master,$userRepository);
  }

And here's the job class:

public function handle()
    {
      $rows = $this->rows;
      $master = $this->master;

      foreach ($rows as $row) {

          $user = $this->userRepository->createUser(//data from the csv);

          // Assign commerce role
          $user->assignRole('commerce');

          $commerce = $this->userRepository->createMinion(
            //data from the csv
          );

          $this->userRepository->bindMinion($user,$minion,$master);

          $commerce->save();
      }
    }

28th May, 2018

ravasaurio started a new conversation Not Interrupt Foreach Loop When An Error Happens. • 4 months ago

I have created a simple system for bulk-importing users via CSV:

//some process to get an array out of the csv

DB::transaction(function () use ($rows) {
    foreach ($rows as $row) {
        User::create([
            //etc
        ]);
    }
});

So right now if an error occurs, I rollback the table.

I have been asked to do this: if an error occurs, the loop must continue and import as much users as possible. Then display the users that didn't get imported because of an error. I don't know how to do this, and I don't know the terms for a good info search.

In the future I will show a preview of the data to be imported, and display errors within it, and ask the user to correct it before the actual importing begins, but still this is a required feature (and a good last line of defense)

Any code, help, tutorial, manual or even the correct term for searching info is deeply appreciated.

27th April, 2018

ravasaurio left a reply on How Does The 'associate' Method Work Behind The Scenes? • 5 months ago

dd($this->user()->can('create commerces'));returns true.

ravasaurio left a reply on How Does The 'associate' Method Work Behind The Scenes? • 5 months ago

I found the problem and now I feel very dumb. After the user is created, on EntityController I was redirecting to the wrong route, one protected by the role middleware for admins only

public function storeCommerce(StoreCommerceRequest $request)
  {
    $this->entityRepository->createCommerce($request->only(
//etc

    ));

    return redirect()->route('admin.entity.users')->withFlashSuccess(__('alerts.backend.users.created'));
  }

And to feel even more dumb, I didn't even posted that line on my issue here...

It works now, but still I don't know why everything would work except the associate() method. any Ideas?

ravasaurio left a reply on How Does The 'associate' Method Work Behind The Scenes? • 5 months ago

I see I provided very little info. Sorry about that.

These are the routes involved in the process:

  Route::group([
    'middleware'  =>  'role:entity',
  ], function (){

    Route::get('create_commerce', '[email protected]')->name('create_commerce');
    Route::post('store_commerce', '[email protected]')->name('store_commerce');

  });

[email protected]:

public function storeCommerce(StoreCommerceRequest $request)
  {
    $this->entityRepository->createCommerce($request->only(
        'first_name',
        'last_name',
        'email',
        'timezone',
        'position',
        'assigned_test',
        'commerce',
        'phone',
        'web',
        'fuc',
        'dba',
        'address',
        'postal_code',
        'city',
        'province',
        'country'

    ));

StoreCommerceRequest:

public function authorize()
    {
        return $this->user()->can('create commerces');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
            'first_name'     => 'required|max:191',
            'last_name'  => 'required|max:191',
            'email'    => ['required', 'email', 'max:191', Rule::unique('users')],
            'position'      =>  'required|alpha',
            'assigned_test' =>  'nullable|numeric|exists:tests,id',
            'commerce'      =>  'required',
            'phone'         =>  'required',
            'web'           =>  'nullable',
            'fuc'           =>  ['required', Rule::unique('commerces')],
            'dba'           =>  'required',
            'address'       =>  'required',
            'postal_code'   =>  'required',
            'city'          =>  'required',
            'province'      =>  'required',
            'country'       =>  'required',
        ];
    }

And finally, EntityRepository->createCommerce:

public function createCommerce(array $data)
    {
      return DB::transaction(function () use ($data) {
        //creates the user
        $user = User::create([
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'timezone' => $data['timezone'],
            'password' => Hash::make(str_random(16)),
            'active' => 1,
            'confirmation_code' => md5(uniqid(mt_rand(), true)),
            'confirmed' => 0,
        ]);

        // Add commerce role
        $user->assignRole('commerce');

        $commerce = Commerce::create([
          'position'      =>  $data['position'],
          'assigned_test' =>  $data['assigned_test'],
          'commerce'      =>  $data['commerce'],
          'phone'         =>  $data['phone'],
          'web'           =>  $data['web'],
          'fuc'           =>  $data['fuc'],
          'dba'           =>  $data['dba'],
          'address'       =>  $data['address'],
          'postal_code'   =>  $data['postal_code'],
          'city'          =>  $data['city'],
          'province'      =>  $data['province'],
          'country'       =>  $data['country'],
        ]);

        //assign new commerce to corresponding entity and user
        $entity = Entity::find(Auth::user()->entity->first()->id);

        $commerce->user()->associate($user);
        $commerce->entity()->associate($entity);

        $licenses = $entity->remaining_licenses;

        $entity->remaining_licenses = $licenses-1;
        //set user type to 'commerce'
        $user->type='commerce';
        //persist data
        $entity->save();
        $commerce->save();
        $user->save();

        event(new UserCreated($user));
        return $user;
      });
    }

The user doing all this stuff has both the entity role and the create commerces permission. Can you see anything here that could require another permission?

26th April, 2018

ravasaurio started a new conversation How Does The 'associate' Method Work Behind The Scenes? • 5 months ago

I am using the spatie/laravel-permission in my project. I am hiding some routes behind their middleware to avoid unauthorized users to use them. But I am having a problem. When I do this:

$profile->user()->associate($user);

as part of the process of creating a user, I get the "You do not have access to do that." alert.

The user gets created, the profile gets created but they do not get associated to each other. If I manually assign the corresponding IDs it works fine.

I am using the associate() method in other part of the application intended to be used by another role and it works fine, so my guess is that the associate()method is trying to do something I don't know and somewhere it's getting rejected by the role/permission middleware.

What could it be?

19th April, 2018

ravasaurio left a reply on Trying To Get Property Of Non-object-Collections • 5 months ago

Thank you! you have been really helpfull. I was about to jump out the window.

ravasaurio left a reply on Trying To Get Property Of Non-object-Collections • 5 months ago

Oh, I did not see your update! with the [0] works. But I don't really know why! with the [0] I should be accessing the first position over and over again right? How I am getting all the attributes of all the tests using allways [0]?

ravasaurio left a reply on Trying To Get Property Of Non-object-Collections • 5 months ago

@tykus That gives me Undefined index: name error.

ravasaurio started a new conversation Trying To Get Property Of Non-object-Collections • 5 months ago

I am creating a collection using this in my controller:

$tests = collect();

foreach($rawData as $data) {
    //some data treatment

    $tests->push([
          [
            'name'                      =>  $name,
            //etc
          ],
        ]);
}

Then I pass it to the view with compact:

return view('test', compact('tests');

If I dd right after the foreachloop, I see this:

Collection {#615 ▼
  #items: array:2 [▼
    0 => array:1 [▼
      0 => array:12 [▼
        "name" => "test"
        //etc
      ]
    ]
    1 => array:1 [▼
      0 => array:12 [▼
        "name" => "test2"
        //etc
      ]
    ]
  ]
}

All the data in there is correct, there are no nulls and everything is just how I need it, so I try to display it on the view:

@foreach($tests as $test)
    {{$test->name}}
@endforeach

and it throws me the Trying to get property of non-object error, highlighting <?php echo e($commerce->name); ?>.

I don't really know what am I missing here.

16th April, 2018

ravasaurio left a reply on A Question About Route Actions In Laravel • 6 months ago

Good thing I found this out now I just have a few routes in my project, thank you all.

12th April, 2018

ravasaurio left a reply on A Question About Route Actions In Laravel • 6 months ago

So there is no reason for me other than readability to use those? or am I falling in bad practices by deleting db records using POST instead of DELETE?

ravasaurio started a new conversation A Question About Route Actions In Laravel • 6 months ago

Ever since I started using Laravel, I have allways used ´Route::get´ and ´Route::post´. Now I have seen in many tutorials people using other verbs such as ´Route::put´, Route::resource´ or ´Route::patch´.

I allways use ´Route::post´ when that route needs to perform some operation on my database based on the information coming from a form but now I am confused. I haven't found any video or tutorial about this and the Laravel docs only mentions some of the available methods but without any explanation, which leads me to think I might be the only one dumb enough to not understand this, or to overthink about this.

Should I be using ´Route::put´ for creating new elements with the data from a form? ´Route::patch´for updating? ´Route::delete´for deleting? and what is ´Route::resource´ for?

And if so, what are the advantages of those over simply using ´Route::post´? Sorry if this question is stupid but it's driving me crazy.

6th April, 2018

ravasaurio started a new conversation Paginating In A View? • 6 months ago

So I have a tests model and a questionsmodel with a many to many relationship defined. Right now, when a user chooses a test, I do this on the controller:

public function showTestQuestions(Test $test)
    {
      return view('test_questions',compact('test'));
    }

Then this on the view to show the questions:

@foreach($test->question as $question)
//etc
@endforeach

I do it this way because on the view, I need the test's name and other attributes, not only the questions. Now my problem is this: some tests are really big and I want to paginate the questions with like 5 per step. I know I can do something like ´Question::paginate(5)´ on the controller, but then I would only get the questions on the view, not the rest of the test's attributes. That is why I want to know if I can paginate the questions once I have them on my view, on that `forealoop. Thank you.

ravasaurio left a reply on Display Specific Form Step After Redirect • 6 months ago

Thank you! my project manager changed his mind so this is no longer required for me, but in case someone gets here with the same problem, know that it works.

4th April, 2018

ravasaurio started a new conversation Display Specific Form Step After Redirect • 6 months ago

I have a view for a multi-step form which is just plain html+css+js based on this template:

https://bootsnipp.com/snippets/featured/form-wizard-and-validation

Each step is a div so naturally when I refresh the page or I redirect to that view from somewhere else, it goes to the first step. Can I automatically display, let's say, the third step after redirecting to that view? Like storing somewhere the step I was on when I closed the page and then return to that step instead of the first one.

ravasaurio left a reply on Required_if Validation Rule With Array Values. • 6 months ago

Hello, I found a way to do it and I will post it here in case someone finds it helpful.

I changed this:

public function rules()
    {
      return [
            'first_name'     => 'required|max:191',
            'last_name'  => 'required|max:191',
            'email'    => ['required', 'email', 'max:191', Rule::unique('users')],
            'timezone' => 'required|max:191',
            'password' => 'required|min:6|confirmed',
            'roles' => 'required|array',
        ];
    }

To this:

public function rules()
    {
      $rules = [
        'first_name'    => 'required|max:191',
        'last_name'     => 'required|max:191',
        'email'         => ['required', 'email', 'max:191', Rule::unique('users')],
        'timezone'      => 'required|max:191',
        'password'    => 'required|min:6|confirmed',
        'roles'         => 'required|array',
      ];

      if(isset(request()->roles))
      {
        if(in_array('commerce',request()->roles))
        {
          $additionalRules = [
            'extra_field_1' =>  'required|alpha',
            'extra_field_2' =>  'required|numeric',
            //etc
          ];
          $rules = $rules+$additionalRules;
        }
      }

      \Log::debug($rules);
      return $rules;
    }

So instead of directly returning the set of rules, I store them on the rulesvariable. Then I check if the rolesarray is present and if it is there, I look for the userstring inside. If userrole was selected, then I create an additional set of rules and combine it with the original one.

This is how ruleslooks like on the logs:

Without userrole selected:

'first_name' => 'required|max:191',
'last_name' => 'required|max:191',
'email' => 
array (
0 => 'required',
1 => 'email',
2 => 'max:191',
3 => 
Illuminate\Validation\Rules\Unique::__set_state(array(
'ignore' => NULL,
'idColumn' => 'id',
'table' => 'users',
'column' => 'NULL',
'wheres' => 
array (
),
'using' => 
array (
),
)),
),
'timezone' => 'required|max:191',
'password'    => 'required|min:6|confirmed',
'roles' => 'required|array',
)

With userrole selected:

'first_name' => 'required|max:191',
'last_name' => 'required|max:191',
'email' => 
array (
0 => 'required',
1 => 'email',
2 => 'max:191',
3 => 
Illuminate\Validation\Rules\Unique::__set_state(array(
'ignore' => NULL,
'idColumn' => 'id',
'table' => 'users',
'column' => 'NULL',
'wheres' => 
array (
),
'using' => 
array (
),
)),
),
'timezone' => 'required|max:191',
'password'    => 'required|min:6|confirmed',
'roles' => 'required|array',
'extra_field_1' =>  'required|alpha',
'extra_field_2' =>  'required|numeric',
)

That way those extra fields are only required when userrole is selected.

27th March, 2018

ravasaurio left a reply on Davejamesmiller/laravel-breadcrumbs - Trying To Get Property Of Non-object • 6 months ago

@rin4ik thank you very much, it works. But I don't quite understand how. Does that public function showTestQuestions(Test $test) automatically find the test with the ID given in the route? and why doesn't Test::find($id)work?

ravasaurio started a new conversation Davejamesmiller/laravel-breadcrumbs - Trying To Get Property Of Non-object • 6 months ago

Hello. I am using this package to manage my breadcrumbs and I wanted to create a breadcrumb for a dynamic page and I am getting that error. This is my route:

Route::get('questions/{test}', '[email protected]')->name('questions.test');

Controller:

public function showTestQuestions($id)
    {
      $test = Test::find($id);
      return view('backend.test_questions',compact('test'));
    }

I have this on my view:

@section('breadcrumbs', Breadcrumbs::render('admin.questions.test', $test))

I have tried this one too:

{{ Breadcrumbs::render('admin.questions.test', $test) }}

The breadcrumb:

Breadcrumbs::register('admin.questions.test', function ($breadcrumbs, $test) {
  $breadcrumbs->parent('admin.tests');
  \Log::debug($test);
  $breadcrumbs->push($test->type , route('admin.tests', $test));
});

That \Log::debug($test); Logs me two separate things:

1-The id of the $test.

TimeHeader 15:39:3815 2-The full info of the $test, including the type, which is what I am trying to access to. TimeHeader 15:39:38{"id":15,"type":"GTR","description":null,"standard":1,"created_at":"2018-03-27 10:47:37","updated_at":null}

20th March, 2018

ravasaurio started a new conversation Required_if Validation Rule With Array Values. • 6 months ago

I have a form for my admin to create new users. This is where the data is validated:

public function rules()
    {
      return [
            'first_name'     => 'required|max:191',
            'last_name'  => 'required|max:191',
            'email'    => ['required', 'email', 'max:191', Rule::unique('users')],
            'timezone' => 'required|max:191',
            'password' => 'required|min:6|confirmed',
            'roles' => 'required|array',
        ];
    }

In my form, there are some switches you may turn on/off to select the roles you want to assign the new user. roleswill be an array containing the role names you have selected. This is how the array looks like on the logs:

array ( 

0 => 'administrator',
1 => 'executive',
2 => 'user',
)

What I need is to have some extra fields required, only if the user role was selected:

public function rules()
    {
      return [
            'first_name'     => 'required|max:191',
            'last_name'  => 'required|max:191',
            'email'    => ['required', 'email', 'max:191', Rule::unique('users')],
            'timezone' => 'required|max:191',
            'password' => 'required|min:6|confirmed',
            'roles' => 'required|array',
        'extra_field_1' => 'required_if:',//<--'user' role was selected? then this field will be required
        ];
    }

I have tried something like this:

'extra_field_1' => 'nullable|required_if:roles,User', 'extra_field_1' => "required_if:roles,==,User",

Testing those, I selected the 'user' role and then left the extra fields empty to see if the validation fails and it doesn`t. Instead I get an SQLexception from trying to insert null data on not null columns (When I send the form, if the roles rule was selected the value of those extra fields will be inserted on a table which is different from the users table).

How can I get that required_if working? Thanks.

19th March, 2018

ravasaurio left a reply on Enable/disable Required Policy From The Laravel Boilerplate Forms Dynamically. • 6 months ago

@xmarks Yes, I may have explained myself wrong, I was confused by the strange look of the form HTML and didn´t find the validation rules until you first replied, sorry for that. Also I sometimes struggle to express myself in english. Right now I think this is the easiest way to describe my problem:

I need to know how can I check if an array contains certain string on a required_if rule, as the 'roles' array simply contains strings with the names of the roles:

'roles' => 'required|array',

'extra_field1' => 'nullable|required_if:' <--the string 'user' is on the 'roles' array? then it is required.

At this point I think it would be better to open a new discussion with this much more focused point of view than the original one, but many thanks to you, you pointed me on the right direction.

ravasaurio left a reply on Enable/disable Required Policy From The Laravel Boilerplate Forms Dynamically. • 6 months ago

@xmarks Hello, sorry it took so long for me to answer, I had to wait the whole weekend to test your solution. It was really helpfull but i'm not being able to implement it. This is my problem. I found the request that validates that form and it looks like this:

public function rules() { return [ 'first_name' => 'required|max:191', 'last_name' => 'required|max:191', 'email' => ['required', 'email', 'max:191', Rule::unique('users')], 'timezone' => 'required|max:191', 'password' => 'required|min:6|confirmed', 'roles' => 'required|array',

So 'roles' is validated to be an array. What I want is my extra fields to be required if the user role is selected (A user can have more than one role, in the form each role is a switch you can check and as you can see you are required to select at least one) so I tried to add something like this:

'extra_field_1' => 'nullable|required_if:roles,User',

or this:

"extra_field_1" => "required_if:roles,==,selling",

or your solution:

extra_field_1 => nullable|required_with:role,

When this form arrives to the function that stores the user, if the user role is selected, it inserts the extra fields value to another table. With this validation attempts, I get an SQL exception from trying to insert null data on not null fields, which makes me think these validation attempts are not working at all. What can I be missing? sorry for the long text.

16th March, 2018

ravasaurio started a new conversation Enable/disable Required Policy From The Laravel Boilerplate Forms Dynamically. • 7 months ago

Hi. I have added some new fields to the Laravel Boilerplate user creation form. Those fields will only display if a certain role is selected when creating a new user. I want those fields to be required, but then when you don't see them, it will not let you send the form because those fields are empty. How can I set those fields required only when they are visible? I've never seen a form like this before:

{{ html()->label(__('validation.attributes.backend.access.users.last_name'))->class('col-md-2 form-control-label')->for('last_name') }}
                        <div class="col-md-10">
                            {{ html()->text('last_name')
                                ->class('form-control')
                                ->placeholder(__('validation.attributes.backend.access.users.last_name'))
                                ->attribute('maxlength', 191)
                                ->required()  //<-enable/disable this}}
                        </div><!--col-->
                    </div><!--form-group-->

15th March, 2018

ravasaurio started a new conversation Relationships Where Something May Or May Not Have Something • 7 months ago

Hey guys, i'm new to laravel and I'm having a hard time understanding eloquent models and relationships.

So I have this database where the user's basic information is stored on the users table, and I have another two tables (commerces and entities) for more specific info depending on what the user is. So I think I need to set in the Commerce and Entity models belongsTo the User model, but I'm not sure if I should set User model hasOne Commerce or Entity as it may or may not have that relationship. How should I proceed? many thanks in advance.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.