pedroborges

pedroborges

Member Since 5 Years Ago

Ribeirão Preto, Brazil

Experience Points 16,050
Experience Level 4

3,950 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 285
Lessons
Completed
Best Reply Awards 3
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

16 Jun
2 years ago

pedroborges started a new conversation Transform Input Data Before Controller

I was looking for a way to transform input data before it hits the database and came up with the solution below. I wanted a central place to do it instead of repeating the same transformations on a bunch of controller methods.

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use App\Http\Requests\TransformRequestTrait;

class CreateInteractionRequest extends Request
{
    use TransformsRequestTrait;

    protected $transformations = [
        'date' => ['completed_at', 'deadline'],
        'hash' => ['aimed_at', 'assigned_to'],
    ];

    protected $rules = [
        'completed_at' => 'required|date_format:d/m/Y|before:now',
        'summary'      => 'string',
        'type'         => 'required|digits:1',
    ];

protected function transformDate($date)
    {
        return Carbon::createFromFormat('d/m/Y', $date);
    }

    protected function transformHash($hash)
    {
        return app('hashids')->decode($hash)[0];
    }

    public function authorize()
    {
        return true;
    }
}

How does it work? First you have to use the TransformsRequestTrait __(see below)__. Then define transformations on the $transformations property and create methods to handle them. A date transformation, for example, will be handle by the transformDate method. Instead of returning validation rules on the rule method, define them on the $rules property.

This solution will validate the input data as it comes from the client but pass the transformed data to the controller. For example, it the client sends:

{aimed_at: "48m33JmT", completed_at: "16/06/2016", summary: "", type: "5"}

The above will be validated according to the rules defined on the CreateInteractionRequest class. But the controller will receive:

    public function store(CreateInteractionRequest $request)
    {
        // array:4 [
        //     "aimed_at" => 18
        //     "completed_at" => Carbon {#283
        //         +"date": "2016-06-16 13:26:28.000000"
        //         +"timezone_type": 3
        //         +"timezone": "America/New_York"
        //     }
        //     "summary" => ""
        //     "type" => 5
        // ]
        return Interaction::create($request->all());
    }
<?php

namespace App\Http\Requests;

use Illuminate\Support\Str;

trait TransformsRequestTrait
{
    protected $transformedInput;

    public function rules()
    {
        if (property_exists($this, 'transformations')) {
            $this->transformedInput = $this->all();
            $this->transform();
            $this->replace($this->transformedInput);
        }

        return $this->rules;
    }

    protected function transform()
    {
        foreach (array_keys($this->transformations) as $transformation) {
            $method = 'transform' . Str::studly($transformation);

            if (method_exists($this, $method)) {
                $this->transformAll($method, $transformation);
            }
        }
    }

    protected function transformAll($method, $transformation)
    {
        $values = $this->transformations[$transformation];

        foreach ($values as $value) {
            if ($this->has($value)) {
                $this->transformedInput[$value] = $this->{$method}($this->input($value));
            }
        }
    }
}

I'm looking for feedback on this solution.

08 Jun
2 years ago

pedroborges started a new conversation Trying To Get Property Of Non-object From Carbon Instance

I have two similar views and yesterday one of them began throwing the Trying to get property of non-object error. It is being caused by $person->born_at->age. The same line on another view worked fine.

@foreach ($people as $person)
    <a href="{{ url('/people', [$person->id]) }}" class="list-group-item">
        {{ $person->name }} ({{ $person->born_at->age }} years-old)
    </a>
@endforeach

The born_at attribute is included in the $dates mutator on the model, so it should be a Carbon instance, and it is. When I dump $person->born_at inside that loop it outputs:

Carbon {#225 ▼
  +"date": "1992-03-16 00:00:00.000000"
  +"timezone_type": 3
  +"timezone": "America/Sao_Paulo"
}

I couldn't find the cause, so I removed that line and moved on. Today, the other view that was worked fine began throwing the same error out of nowhere. I'd appreciate any help!

15 Dec
3 years ago

pedroborges left a reply on Session Missing 'errors' Key In PHPUnit

I gave up trying to find a solution for this. I'm testing Laravel 5.2 now, I'll let you know if it works.

14 Dec
3 years ago

pedroborges left a reply on Eager Loading?

The with should be used when querying a model, like so: User::with('team')->get().

In this case, since the authenticated user has already been retrieved, you can use the load method: Auth::user()->load('team')

07 Dec
3 years ago

pedroborges started a new conversation Session Missing Key In PHPUnit

I can't get the $this->assertSessionHasErrors(); assertion to work.

$this->visit('/signup');

$this->submitForm('Create my account', [
    'name'       => '',
    'email'      => 'pedro',
    'cellphone'  => 1698149,
    'password'   => 123,
    'password_confirmation' => 123
]);

$this->seePageIs('/signup');
$this->assertSessionHasErrors(); // this fails

If I $this->dump() the page it shows all the errors messages when the validation fails. It also works correctly in the browser. But when running phpunit all I get is:

Session missing key: errors
Failed asserting that false is true.

I also tried dumping $this->app['session.store']:

#attributes: array:4 [
  "_token" => "2hGrgYb0manQcPBpwi60BFozLnBBMAx0hYJVfEH3"
  "_previous" => array:1 [
    "url" => "http://localhost/signup"
  ]
  "flash" => array:2 [
    "old" => []
    "new" => []
  ]
  "_sf2_meta" => array:3 [
    "u" => 1449505334
    "c" => 1449505334
    "l" => "0"
  ]
]

In my routes.php I have this code after the validation:

if ($validator->fails())
{
    return redirect('/signup')
                ->withInput()
                ->withErrors($validator);
}

I'm using 5.1 fresh installed yesterday.

17 Nov
3 years ago

pedroborges left a reply on Testing My App "in The Future"

Actually there's a package for that: composer require rezzza/time-traveler

See: [https://github.com/rezzza/TimeTraveler]

I haven't used it but it seems to do what you want.

13 Nov
3 years ago
27 Feb
4 years ago

pedroborges left a reply on Bests PHP Framework Of 2015 Survey

@willvincent They used Typeform for that questionnaire. It was weird to me too, but the keyboard did the trick.

pedroborges started a new conversation Bests PHP Framework Of 2015 Survey

Last year Laravel was chosen the best PHP framework on a survey led by SitePoint.

It's time to choose this year's winner. Go Laravel!

Best PHP Framework of 2015

25 Feb
4 years ago

pedroborges left a reply on Events - Who's The Benefactor? (behat)

Checkout Sylius features as an example. Lot's to learn from there.

22 Feb
4 years ago

pedroborges left a reply on Eloquent VS Query Builder Responses

When you use $foo = Bar::find(1) it returns an Eloquent model object, you can make it an array: $foo->toArray().

$foo = Bar::all() on the other hand returns a Collection of models, which provides some nice methods to work with multiple itens. You can also make a simple array out of it: $foo->toArray().

But if you are using the Query Builder to get multiple itens an wants a Collection, you can too:

$users = DB::table('users')->all();

$collection = new Illuminate\Database\Eloquent\Collection($users); // pass an array
21 Feb
4 years ago

pedroborges left a reply on The History

There are a few interviews where he talks about it:

If it was hard to convince people to use it, not that much. I saw a tweet about Laravel on it's first week and loved it after reading through the docs. After a little while Taylor started announcing new features and gathering feedback on Forrst, see his posts: http://zurb.com/forrst/people/taylorotwell. There you can see people first reactions.

pedroborges left a reply on Binding String Of Ids To DB::raw WHER IN

If the Query Builder is an option, why not do:

DB::table('projects')
    ->select('id', 'title', 'description')
    ->whereIn('id', $inputIds) // pass an array
    ->groupBy('id')
    ->orderBy('id', 'ASC')
    ->get();
14 Feb
4 years ago

pedroborges left a reply on Postgresql Statement Syntax Error

Thanks for the reply @fideloper. Yeah, I learned a lot digging in the Laravel's DB classes today before posting here. A few of your posts helped a lot!

I'll post here if I find an answer.

pedroborges started a new conversation Postgresql Statement Syntax Error

So I've trying to get the most out of Postgresql new features using Laravel, but given the lack of information out there about Laravel with Postgresql, it hasn't been an easy task.

I have migrated my DB successfully, including one table which has a profile field, of JSONB data-type. Eloquent inserts new records perfectly, but I can't run the following query: App\Person::whereRaw('profile ? \'email\'')->get();. It seems like tries to bind a param to the query.

Illuminate\Database\QueryException with message 'SQLSTATE[42601]: Syntax error: 7 ERROR:  syntax error at or near "$1"
LINE 1: select * from people where profile $1 'email'
                                           ^ (SQL: select * from people where profile ? 'email')'

For those not familiar, the ? operator check the existence of a key in a Postgresql JSONB data-type. It works fine when run on pgsql CLI: select * from people where profile ? 'email'

Any ideas?

12 Feb
4 years ago

pedroborges left a reply on Laravel Elixir Depending On Environment

The docs recommends that you use the production flag when running Gulp in production: gulp --production. Internally, Elixir defines the variable below to check the environment and modify the behaviour of certain recipes:

var inProduction = elixir.config.production

You could add the line above to your Gulpfile and to the check yourself.

var elixir = require('laravel-elixir');

var inProduction = elixir.config.production;

elixir(function(mix) {
    mix.sass("bootstrap.scss");

    if (! inProduction) {
        // Do the BrowserSync stuff…
    }
});

I haven't tested this, so please let me know if that works.

10 Feb
4 years ago

pedroborges left a reply on You Can Now Autocomplete Usernames

@JeffreyWay Cool! What about sorting by experience and also show people already in the conversation first?

03 Feb
4 years ago

pedroborges left a reply on [L5] .env Understanding

Behind the scenes, Laravel uses PHPdotenv. It's readme says:

phpdotenv is made for development environments, and generally should not be used in production. In production, the actual environment variables should be set so that there is no overhead of loading the .env file on each request. This can be achieved via an automated deployment process with tools like Vagrant, chef, or Puppet, or can be set manually with cloud hosts like Pagodabox and Heroku.

You don't need that file in production because all PHPdotenv does is merge the file's variables with server's variables to be used like getenv('S3_BUCKET'); or $_ENV['S3_BUCKET'];. On production, set the variables on the server.

16 Oct
4 years ago

pedroborges left a reply on How Do I Gulp Both Css (less) And Javascript?

Actually you don't need the second argument if your scripts are on the public directory, you could do:

mix.scripts('js/**/*.js') // public/js/app.js

If you are combining scripts, just remove the scripts task and add your file to the version task.

pedroborges left a reply on How Do I Gulp Both Css (less) And Javascript?

Just like the less task, Elixir provides a scripts task, but you have to specify the file path and source directory.

elixir(function(mix) {
    mix.less('app.less')
       .scripts('*.js', 'resources/assets/js')
       .version(['css/app.css', 'js/all.min.js']);
});

If you don't want to concatenate all scripts, just pass the file name instead of the wildcard.

Elixir also offers a coffee task, if you prefer Coffee-Script.

13 Oct
4 years ago

pedroborges left a reply on How To Exit The Tinker Console?

exit(); (with semicolon) also did it for me.

08 Oct
4 years ago

pedroborges left a reply on How To Use Middleware As Filters?

@maxccarvalho Have you tried @Middleware("auth", except="getLogout")?

07 Oct
4 years ago

pedroborges left a reply on Laravel 4.2 To Laravel 5 Migration

You can compare the develop branch to the master one to find out which files changed: [https://github.com/laravel/laravel/compare/master...develop]

But be aware changes are still being made and stuff can break. If you adopt L5 now, keep an eye on the Github repo.

06 Oct
4 years ago

pedroborges left a reply on Route Annotation In Laravel 5

@anzze You are right! Routes as we know it aren't going anywhere.

05 Oct
4 years ago

pedroborges left a reply on Route Annotation In Laravel 5

Taylor suggested to use a watcher to rescan routes when any file inside app/HTTP/Controllers changes. I would also suggest to recreate a routes file with that watcher for better reference, like: php artisan route:list > app/HTTP/routes.txt.

Is it easy to run a command like that with Gulp?

04 Oct
4 years ago

pedroborges left a reply on Route Annotation In Laravel 5

@jacob It's indeed a cool feature. Taylor also made very flexible so people can use it along with the routes file. Routes defined in annotation are also listed when you run the route:scan command.

pedroborges started a new conversation Route Annotation In Laravel 5

Laravel 5 now includes route annotation. That means now you can have a controller like this:

<?php namespace App\Http\Controllers;

use Illuminate\Routing\Controller;

/**
 * @Resource("foobar/photos", only={"index", "update"}, names={"index": "index.name"})
 * @Controller(domain="{id}.account.com")
 * @Before("auth")
 * @Before("csrf", on={"post", "put", "delete"})
 * @Where({"id": "regex"})
 */
class BasicController extends Controller {

    /**
     * @Before("inline")
     * @return Response
     */
    public function index() {}

    /**
     * @Before("inline")
     * @After("inline")
     * @return Response
     */
    public function update($id) {}

    /**
     * @Put("/more/{id}", after="log")
     */
    public function doMore($id) {}

}

Then you have to run php artisan route:scan and Laravel will cache all annotated routes in `storage/framework/routes.scanned.php

What do you guys think of this feature?