pedroroccon

pedroroccon

Lead Developer at BYUS Technology

Member Since 4 Years Ago

Rio Claro

Experience Points
26,740
Total
Experience

3,260 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
203
Lessons
Completed
Best Reply Awards
1
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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,740 XP
Dec
14
1 month ago
Activity icon

Awarded Best Reply on O.o I Have No Idea Reason Why

@paboo You need to make a "foreach" inside your tbody like this:

<tbody>
    @foreach($adc as $item)
        <tr>
            <th></th>
            <th>{{$item->id}}</th>
            <th>Email</th>
            <th>Age</th>
            <th>Marries</th>
            <th>Address</th>
            <th>Points</th>
            <th><button type="button" class="btn btn-danger">Remove</button>
            <button type="button" class="btn btn-primary">Edit</button></th>
        </tr>
    @endforeach
</tbody>
Dec
04
1 month ago
Activity icon

Replied to Disable Global Query Scope On Specific Controller

@snapey and @srinathdudi Thanks for the reply!

I liked the two solutions, but I liked the @srinathdudi solution. Simply adds a protected variable in the controllers that needs to disable the global query scope.

Thank you! Regards!

Dec
03
1 month ago
Activity icon

Started a new Conversation Disable Global Query Scope On Specific Controller

Greetings,

I created a global query scope in one of my models. The scope is called "waiting", and it is used to indicate that a follow resource is waiting to be approved.

    protected static function boot()
    {
        static::addGlobalScope('waiting', function(Builder $builder) {
            $builder->where('waiting', false);
        });
    }

I separated the approved resources in one specific view wich is associated to a controller. Then I created another controller wich will display all the "waiting" resources.

I know that I can disable the global scope temporarily, but there's a way to disable the global query scope in all methods of my controller. Later I'll need to implement more methods?

Regards!

Nov
08
2 months ago
Activity icon

Replied to Dealing With Git - Main Package And Subpackages

@aurawindsurfing Hmm, nice idea. I'll give it a try. I thought that Git has some solution to do that.

Nov
07
2 months ago
Activity icon

Started a new Conversation Dealing With Git - Main Package And Subpackages

Greetings

I have a main package called "Core" which is a Laravel installation with some custom modifications. My "Core" package depends on a series of other packages that I made. For example: "core-products", "core-customers", "core-invoices", etc... I made that way to reuse those modules in another projects, like a modular application.

My problem with GitHub is: I need to handle my repositories inside the vendor/pedroroccon/core-... folder, and everytime I change something, I init, and commit each package individually

Theres a way to commit my main "Core" project and the Git commits my dependencies too? Maybe with submodules?

Regards,

Oct
17
3 months ago
Activity icon

Replied to Laravel With PostCSS And Laravel Mix

@siangboon OMG I haven't saw that. Thank you very much!

Regards!

Oct
16
3 months ago
Activity icon

Started a new Conversation Laravel With PostCSS And Laravel Mix

Greetings!

Anyone knows how to use PostCSS in a standard Laravel installation? I'm using Laravel Mix. Here is my webpack.mix.js file:

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css').options({
        processCssUrls: false 
    })
    .copyDirectory('resources/images', 'public/images')
    .copyDirectory('resources/fonts', 'public/fonts')
    .browserSync('localhost:8000');

Regards!

Sep
26
3 months ago
Activity icon

Replied to Help With VSCode Regex Search

@tray2 You helped me a lot. I made just a simply adjust in you code:

count\(\$\w+->\w+\)

I Added a \ before the $, because VS Code is recorgnizing the $ as a Regex command.

Edit: Hmm... I think that you didn't forget the \. The Laracasts forms splitted the \ from you code.

Thank you! Regards!

Activity icon

Replied to Help With VSCode Regex Search

@tray2 Unfortunately didn't work. It returns me 0 results. There is a website or something that I can test the Regex?

I wan't to get something like this:

count($order->products)
Activity icon

Started a new Conversation Help With VSCode Regex Search

Greetings,

I'm having trouble with Regexp searches in VS Code. I need to search in my package files with the following sentence:

count({anything}->{anything))

Usually I use the https://www.debuggex.com/ to debug my regexp, but the syntax isn't the same.

How can I do that with VS Code Regexp?

Thanks! Regards,

Sep
13
4 months ago
Activity icon

Replied to Laravel And Thermal Printers

@tykus Awesome! You simplified a lot. I'll keep your first idea, but with the Laravel Zero. Thanks for the support!

Activity icon

Replied to Laravel And Thermal Printers

@skauk I can only send the print layout through a file in a command line, because the browser doesn't support RAW prints. Basically the browser send the following code as a string to the printer and not interpret the PCLA, PCLB, PCLZ commands like:

^CFA,30
^FO50,300^FDJohn Doe^FS
^FO50,340^FD100 Main Street^FS
^FO50,380^FDSpringfield TN 39021^FS
^FO50,420^FDUnited States (USA)^FS
^CFA,15
^FO600,300^GB150,150,3^FS
^FO638,340^FDPermit^FS
^FO638,390^FD123456^FS
^FO50,500^GB700,1,3^FS

I read about this, and found some extensions that prints RAW files in the Chrome, but I don't want to depend of a extensions and specifique browsers.

Activity icon

Replied to Laravel And Thermal Printers

@tykus Great! I agree that this forum isn't the best place to get the answers. I started this thread just for get some ideas. I was thinking that maybe someone already made that in a easier way.

Maybe i'll stick with your first ideia and install a local webserver in my customer computer.

However I appreciate the support! Thanks

Regards,

Activity icon

Replied to Laravel And Thermal Printers

I was thinking in something like a desktop application, or something more "encapsulated".

To execute this solution, I'll need to install in my customer a local webserver, with php, and all the other stuff.

I get the ideia, but i'm trying to simplify a little more.

Activity icon

Replied to Laravel And Thermal Printers

Hmm nice! Unfortunately I need a simpler solution because it's not me that'll use the applications. Something more intuitive.

Activity icon

Started a new Conversation Laravel And Thermal Printers

Greetings,

I'm developing an application that's hosted on a webserver. My application simples get a user input and them print that on a thermal printer (Argox OS2140). The problem is: The app is hosted on a remote server, but the thermal printer is locally installed on my computer.

Anyone knows a solution that I can integrate the local thermal printer in my web application? The difficult is find a way to print the generated file, as the thermal printer accepts only command line and my remote server can't send the command to my local computer.

Regards,

Aug
30
4 months ago
Activity icon

Replied to User Profile Image Needs To Return A Default "no-photo" Image

I simplified a bit

public function profile()
{
    return $this->photos()->where('cover', true)->first() ?? new UserPhoto(['file' => 'no-image.jpg']);
}
Activity icon

Replied to User Profile Image Needs To Return A Default "no-photo" Image

Works really great for me. Really nice, I didn't notice I can simple create a object and associate a default image to that!

Thank you!

Regards!

Activity icon

Replied to Best Way To Specify New Items

The latest() method will add a orderBy('created_at', 'desc') in your query. You can specify a different field by doing: latest('table_field')

For example:

User::latest();
// SELECT * FROM users ORDER BY created_at DESC

User::latest('last_login_at')
// SELECT * FROM users ORDER BY last_login_at DESC
Activity icon

Started a new Conversation User Profile Image Needs To Return A Default "no-photo" Image

Greetings

Basically I have 2 models: User and UserPhoto. A User has many photos, but only one is marked as profile photo. I want to display the profile photo only if it is associated. Otherwise I'll display an default "no-photo" image.

class User extends Model
{
    public function photos()
    {
        return $this->hasMany(UserPhoto::class);
    }

    public function profile()
    {
        return $this->photos()->where('cover', true)->first();
    }
}

class UserPhoto extends Model
{
    
    public function toHtml()
    {
        return $this->file;
    }
}

My problem is: I need to call a method inside the UserPhoto, but if there is no profile photo associated, the application return me Trying to get propety of a non object. I really don't want to check everytime if my function returns null, like !empty($user->profile()) ? $user->profile()->toHtml() : 'path_to_image'

<!--
    The problem: The profile image is optional.
    If there's no profile image, the follow 
    code will return "Trying to get property of 
    a non object".
-->
<img src="{{ asset($user->profile()->toHtml()) }}">

There is a better aproach to make that without checking every time if the function returns me the object? Maybe using calbacks or something like that.

$user->profile(function($p) {
    return $p->toHtml(); // If not exists, returns default image.
});

Thank you! Regards!

Activity icon

Replied to Query Strings Dynamically Updates Inputs In Form

@cometads It works!

I'm developing a real time application with some filters, and I want to pass the query strings in my URL to my variables inside Vue.js.

Thanks for helping me!

Aug
29
4 months ago
Activity icon

Started a new Conversation Query Strings Dynamically Updates Inputs In Form

Greetings!

I'm very new with Vue.js, and i'm stuck with a problem that involves forms and dynamically updates of query strings.

Let's assume that I have a server running in localhost:8000

My index.php have just 2 inputs:

<input name="foo" v-model="foo">
<input name="bar" v-model="bar">

I want that every changes made in inputs FOO and BAR will be reproduced in the query string of my URL.

For example, if I access the page with localhost:8000?foo=Hello my <input name="foo"> automatically populates with the value in my query string.

Here is my code (very simple):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue Router - Testing</title>

    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
    <div id="app">
        <h1>Vue Router - Query string</h1>
        <hr>
        <input type="text" v-model="foo">
    </div>

    <script>
        const routes = [
            { path: '/' }
        ];

        const router = new VueRouter([
            routes
        ]);

        const app = new Vue({
            router,     
            el: '#app', 
            data: {
                foo: 'foo', 
                bar: 'World', 
            }, 
            mounted() {
                console.log('ok');
                console.log(this.$router.query); // Returns me UNDEFINIED
            }
        });
    </script>
</body>
</html>

Someone can help me? Regards!

Activity icon

Replied to Is Worth Using Laravel Mix + Vue For Simple Applications? (migrating From JQuery)

@snapey Thanks for reply!

It seems that depends a lot of the application that we are building. For my project I'll keep the solution of @snapey.

In my application, I included the app.js and used the Vue inline (without creating a component), because the app.js includes de AXIOS too.

Thanks for the support!

Regards!

Aug
27
4 months ago
Activity icon

Replied to Is Worth Using Laravel Mix + Vue For Simple Applications? (migrating From JQuery)

@mabdullahsari @cronix

Hmm, In my case I'm developing a small application, so I need to add some javascripts.

To demonstrate:

I have a form with 3 fields: Brand, Vehicle and Models.

When I change my brand, the Vue uses axios to consume an API that returns me the Vehicles associated to this brand. Same thing when I change the Vehicle, the API returns me the associated models.

Well, I'm using the Vue, JUST FOR THAT. In my concept there is not advantages creating an component just for that. I wrote my Vue code inline in an example, but i'm having dificults now trying to transport that to Laravel and Laravel Mix envoriment. Here is my sample:

https://github.com/pedroroccon/vue-axios-populate-selects

To reproduce that I'll need to creat a component?

Regards!

Aug
23
4 months ago
Activity icon

Started a new Conversation Is Worth Using Laravel Mix + Vue For Simple Applications? (migrating From JQuery)

Greetings!

I'm changing from jQuery to Vue.js using Laravel and Laravel Mix to compile my assets.

My application has only one page that needs to dynamically populate a select input. I already developed and tested that with Vue, but outside of Laravel enveiroment (importing the Vue CDN on a single html file). Now I need to migrate that to my Laravel application.

Laravel uses Mix to compile all my javascripts into a app.js (which is loaded in every view).

My question: Is worth to have this piece of code that will be always loaded in my application just because I use that in ONE PAGE? I'm really confused about using Vue Components for everything. In jQuery I just open a tag and made the necessaries changes for the page.

Regards,

Aug
12
5 months ago
Activity icon

Replied to PHPUnit Returning 404 After First GET Request

@talinon

That is a much better approach!. Thanks for sharing this content with us. I'll change my code!

Aug
09
5 months ago
Activity icon

Replied to PHPUnit Returning 404 After First GET Request

@talinon and @au

Thank you very much! Saved my life!

I have splitted my route files in web.php and sys.php (for admin pages). I solved the problem replacing require_once to require, as your link suggest. Everything works fine now!

Auth::routes();

// Changed require_once to require
require 'sys.php';

Route::get('/', function () {
    return view('welcome');
});

Route::get('/home', '[email protected]')->name('home');

And now, here is my PHPUnit:

phpunit

PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

..........................................                        42 / 42 (100%)

Time: 1.94 seconds, Memory: 38.00 MB

OK (42 tests, 42 assertions)

Thank you again :) Helped me a lot!

Activity icon

Replied to PHPUnit Returning 404 After First GET Request

I'm sorry, I changed my code but didn't changed here.

@aurawindsurfing and @talinon

The $this->sysPath simples returns 'app'. I changed the admin to app. Even if I hardcode the test path, It keeps failing. What can't figure out is why when I run a single test it passes, but when I run the entire test class it fails in my second GET request.

If I run: phpunit --filter=has_index it returns me success

If I run: phpunit --filter=has_create_form it returns me success

But, if I run: phpunit --filter=OrganizacaoCrudTest the second method, it returns me 404 error.

I updated my class changing the admin to app. Both requests paths are valids. Here is the code updated, but with same error

<?php

namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Sys\Organizacao;

class OrganizacaoCrudTest extends TestCase
{
    use RefreshDatabase;
    protected $organizacao;
    protected $user;

    public function setUp() : void
    {
        parent::setUp();
        $this->organizacao = factory(Organizacao::class)->create();
        $this->user = factory('App\User')->create();
    }

    /** @test */
    public function has_index()
    {
        $this->actingAs($this->user)->get('app/organizacao')
            ->assertStatus(200);
    }

    /** @test */
    public function has_create_form()
    {
        $this->withoutExceptionHandling();
        $this->actingAs($this->user)->get('app/organizacao')
            ->assertStatus(200);
    }
}
Aug
08
5 months ago
Activity icon

Replied to PHPUnit Returning 404 After First GET Request

@aurawindsurfing Hello!

I added the withoutExceptionHandling()

    public function setUp() : void
    {
        parent::setUp();
        $this->organizacao = factory(Organizacao::class)->create();
        $this->user = factory('App\User')->create();
    }

    /** @test */
    public function has_index()
    {
        $this->actingAs($this->user)->get($this->sysPath . '/organizacao')
            ->assertStatus(200);
    }

    /** @test */
    public function has_create_form()
    {
        // Added
        $this->withoutExceptionHandling();
        $this->actingAs($this->user)->get($this->sysPath . '/organizacao')
            ->assertStatus(200);
    }

Here is my PHPUnit output

phpunit --filter=OrganizacaoCrudTest

PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

.E                                                                  2 / 2 (100%)

Time: 515 ms, Memory: 20.00 MB

There was 1 error:

1) Tests\Feature\OrganizacaoCrudTest::has_create_form()
Symfony\Component\HttpKernel\Exception\NotFoundHttpException: GET http://localhost/app/organizacao

/var/www/caob-app/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithExceptionHandling.php:118
/var/www/caob-app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:326
/var/www/caob-app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:120
/var/www/caob-app/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:347
/var/www/caob-app/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:170
/var/www/caob-app/tests/Feature/OrganizacaoCrudTest.php:36

ERRORS!
Tests: 2, Assertions: 1, Errors: 1.

Again, if I try to execute only the has_create_form, it returns me success.

phpunit --filter=has_create_form

PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 488 ms, Memory: 20.00 MB

OK (1 test, 1 assertion)

Any ideia?

Activity icon

Started a new Conversation PHPUnit Returning 404 After First GET Request

Greetings!

I'm getting an error 404 in my PHPUnit Tests. After doing my first GET Request, every next requests returns a 404 error. To make easier to understand, I made 2 methods with exactly same tests.

The first test returns me success, but the second fails with 404 error. If I try to run the second test alone, it returns me success!

Someone knows how to fix that? Thanks :)

My test class:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Sys\Organizacao;

class OrganizacaoCrudTest extends TestCase
{
    use RefreshDatabase;

    protected $organizacao;

    protected $user;

    public function setUp() : void
    {
        parent::setUp();
        $this->organizacao = factory(Organizacao::class)->create();
        $this->user = factory('App\User')->create();
    }

    /** @test */
    public function has_index()
    {
         // Returns success.
        $this->actingAs($this->user)->get('admin/organizacao')
            ->assertStatus(200);
    }

    /** @test */
    public function has_create_form()
    {
         // Running this test alone, returns success, but when I run the entire class, this method fails (404 error)
        $this->actingAs($this->user)->get('admin/organizacao')
            ->assertStatus(200);
    }
}

My PHPUnit Return

phpunit --filter=OrganizacaoCrudTest

PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

.F                                                                  2 / 2 (100%)

Time: 547 ms, Memory: 22.00 MB

There was 1 failure:

1) Tests\Feature\OrganizacaoCrudTest::has_create_form
Expected status code 200 but received 404.
Failed asserting that false is true.

/var/www/caob-app/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:151
/var/www/caob-app/tests/Feature/OrganizacaoCrudTest.php:36

FAILURES!
Tests: 2, Assertions: 2, Failures: 1.

Jul
25
5 months ago
Activity icon

Replied to This Action Is Unauthorized. For All User Except User Have Id Of 2

@ Like this:

public function boot() {
    $this->registerPolicies();
}

Just remove the Gate::before from boot() method, inside the AuthServiceProvider class. This condition is telling to application that only user with ID 2 can do the action.

Jul
23
5 months ago
Activity icon

Replied to PHPUnit Not Running From Vendor/bin Folder (Composer Install)

@diegoaurino I'm running the PHPUnit from a command line. I solved the problem updating my local installation of PHPUnit and running directly from the base installation instead of /vendor/bin/phpunit.

I'm doing phpunit vendor/pedroroccon/my-package instead of vendor/bin/phpunit vendor/pedroroccon/my-package

When I execute composer install it gives me a message telling that everything is up-to-date.

Althought thanks for helping me!

Jul
21
5 months ago
Activity icon

Started a new Conversation PHPUnit Not Running From Vendor/bin Folder (Composer Install)

Greetings,

I have my application setted up and everything is working, but when I try to test using my PHPUnit file (inside the vendor/bin folder), it returns me:

You need to set up the project dependencies using Composer:

    composer install

You can learn all about Composer on https://getcomposer.org/.

Anyone knows what i'm doing wrong? I'm using the command: vendor/bin/phpunit vendor/pedroroccon/my-package to execute the tests

Activity icon

Replied to Image URL Works In Local Serve But Fails In Staging Environment

Can you show us your output? Try typing php artisan --version just to check if artisan is working

Jul
20
5 months ago
Activity icon

Replied to How To Validate Multiple Different Fields Using Only One Request?

Try to add this method in your Request:

public function failedValidation(Validator $validator)
{
    throw new HttpResponseException(
        response()->back()->withErrors($validator->errors()->first()
    );
}

Not validated, needs test

Activity icon

Replied to Caching Company Informations

@snapey I thought about that, but i'm not comfortable doing this because all my company informations will be stored right in the session. But caching results will do the same thing, right?

Jul
19
5 months ago
Activity icon

Started a new Conversation Caching Company Informations

Greetings, In my application I have a model called Company.php which stores always 1 row with company informations. I use this table to retrieve the company's informations and inject in another classes (instead of using a config file).

Here's the problem: Every class that needs that I need to inject that company model, I need to do:

Company::first();

There's a way to make that more efficiently? Maybe caching the result in a session, or creating a class to manage that?

Currently i'm doing a middleware with Cache:

<?php

namespace Pedroroccon\App\Middleware;

use Pedroroccon\App\Company;
use Cache;
use Closure;

class CacheCompanyInformationsMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if ( ! Cache::has('company')) {
            Cache::remember('company', 7200, function() {
                return Company::first();
            });
        }
      
        return $response;
    }
}

In my classes:

<?php

namespace Pedroroccon\App\CustomClass;
use Pedroroccon\App\Company;

class CalculateTaxes
{
    public function __construct(Company $company) {
        // ...
    }
}


// Calling the class
$taxes = new CalculateTaxes(cache('company'));



Thanks!