EliasSoares

EliasSoares

Member Since 4 Years Ago

Fortaleza

at iGet

Experience Points 49,080
Experience Level 10

920 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 219
Lessons
Completed
Best Reply Awards 39
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.

19 Nov
2 years ago

EliasSoares left a reply on TDD - How To Test Controller Validation?

@Kandown

I didn't solved this problem, not in a "beauty way".

I just check if my ClientRequest has the right (expected) validation rules, and trust that Laravel Validation is working as expected.

I've also created an abstract test to do this tests, where the rules order isn't important.

Also you can create a test for each validation on your controller, but this will be very exhaustive, since some models have 20~30 fields, each with 1~3 validation rules, and some rules are complicated to test...

07 Oct
2 years ago

EliasSoares left a reply on Laravel Table Names Are Plural By Default

@jstnbr How do you name a variable on your code that contains a collection of users?

I name it $users, because when I need to do a foreach, I can name the item $user. Otherwise, I'll need to name the item variable of $item, or $aux, or $anythingElseThatDoesNotExplainsWhatsOnThisVariable

I know, we almost never write down the database table names. But when I need to write it, I want a consistency on that table name and my code.

Also, what's the cost os an additional s on my tables name of a database with 1000 table? Less then 1KB of storage? I keep with the comprehensibility.

29 Aug
2 years ago

EliasSoares left a reply on How Do You FTP Into Your Forge Server?

Do you have any FTP server instaled on your forge server? Is your firewall allowing ftp port?

26 Aug
2 years ago

EliasSoares left a reply on Wrong Ownership After Deploy

Solved by adding chown -R :www-data . at sudoers file for envoyer group.

EliasSoares started a new conversation Wrong Ownership After Deploy

Hi,

I've configured my own www server (not forge), and I'm using Envoyer to deploy.

I one project specifically, my application is under src folder on git repository. So I applied an after clone deployment hook to move release/src to release.

That's my hook:

shopt -s extglob
cd {{ release }}
rm -rf !(src)
mv src/* .

The problem is that after this, the files ownership goes to myuser:myuser instead of myuser:www-data, so my files cannot be accessed by the web server.

How can I solve this?

24 Aug
2 years ago

EliasSoares left a reply on Laravel Not Redirecting After Manual User Authentication?

Why are you using redirect guest? And you are not using password to login?! Also your code has not a fallback... so if the user is not found (do not enter on the IF, a blank page will be shown!

23 Aug
2 years ago

EliasSoares left a reply on Returning Array Of Flags

How are this boolean flags stored on model? One boolean attribute for each flag? Could you explain better your model structure and your expected array?

22 Aug
2 years ago

EliasSoares left a reply on Creating An E-Commerce Website On Laravel

Just to have another (and more fair) answer:

I'm pretty sure that with some practice, you can do it! My first answer, I'm focusing on "It's possible to create an secure, user friendly and fully working e-commerce?".

An e-commerce application is very fun to create, but don't think that's so simple.

If you really want to do this, first organize your ideas, write down the project requirements, break it on some small incremental versions.

Learn how to organize your project on Git, how to doccument properly (PHPDocs, nice variable and method names), if possible, learn SOLID principles .

If you will not do this for your client, do it for yourself, and for the community! It's one of the best ways to learn. When you finish your first version, you may feel need to re-create more organized, do it until you look your code and feel good! :)

EliasSoares left a reply on Creating An E-Commerce Website On Laravel

Being realist, no, you will not deliver this ecommerce in 3 weeks.

Even with large experience on Laravel, and e-commerce, I'm not able to do this.

Many things are envolved, security, inventory, payment, shipping...

EliasSoares left a reply on Transulation Manager Install In Laravel 5.0

@Sagarreddy post full error stack!

Not sure without the error stack, but i think that you are using Barryvdh\TranslationManager\Controller class on some controller without importing the class (use Barryvdh\TranslationManager\Controller)

EliasSoares left a reply on Strange Behaviour With Eloquent

public function getPointsAttribute()
    {
        $points = 0;
        foreach ($this->votes AS $vote) {
            $points = $vote->status == 'upvote' ? $votes + 1 : $votes - 1;
        }
        return $points;
    }

The error message is clear: What is $votes?

$votes variable does not exists on your method context, so how will this work? :)

EliasSoares left a reply on Booting Trait On Eloquent Model

This happens because you are declaring a method to the Model, not to the Query builder.

To have you search method acessibile on your Query, you will need to turn it on a scope.

namespace App;


trait SearcheableCategorie
{

    protected $cat;
    protected $model;


    public function scopeSearch()
    {
        $query = $query->where('CAT_therm', '=' , '1');
    }

   
}

Also your method scopeSearch is wrong, since it's not returning anything. It should be:

    public function scopeSearch()
    {
        return $query->where('CAT_therm', '=' , '1');
    }

EliasSoares left a reply on Form Post Submit Treated As Get

Your webserver configuration is wrong!

Your domain localhost should point to /path/to/your/project/public, so when you hit http://localhost/ you will get your route correctly.

If you have many projects running on localhost, just create another domain alias on your hosts file (/etc/hosts on linux) to use exclusively to your project.

20 Aug
2 years ago

EliasSoares left a reply on Form Post Submit Treated As Get

Hey, you can use Github Flavored Markdown to make your posts (and the code snippets) pretty! Take a look at this guide: https://guides.github.com/features/mastering-markdown/

The answer:

You need to define the method at your form declaration:

{!! Form::open(array('url' => '/', 'method' => 'post')) !!}

Also, if you are using PHP > 5.4, you can use short array notation:

{!! Form::open(['url' => '/', 'method' => 'post']) !!}

EliasSoares left a reply on IOC From Controller

Try import the facade:

use \App;

Or simply do

\App::version ()

EliasSoares left a reply on Convert Data Back Into A Model

I'm on mobile now, but I'm pretty sure that Eloquent Model have a hydrate method that creates a collection from an array.

EliasSoares left a reply on Your Thought On PHP 7 At The Crossroad

Oh god! How did nobody thought this before???

Why do you think that millions of websites, web applications runs over PHP?

Of course that isn't faster than a compiled language! Just an idiot do belive that any parsed language will be so fast as an native language.

PHP is widely used becaus it's a very powerful language, easy to understand, simple to learn and relativelly fast! Yes, fast! Facebook was a big example of this. They used PHP for a lot of time, and I think that they just migrated because they have a BILLION of users.

Do any of your projects have at leas a fraction of this size? No? Okay, bye!

19 Aug
2 years ago

EliasSoares left a reply on Laravel Is Really That Slow?

My worst requests takes 150ms. Digital Ocean droplet, PHP 7.0 and MySQL 5.7.

If you are doing this tests on homestead, thats the reason of slowness.

But, if your queries are not optimized or you dont eager load your relations, you will really (and obviously) have bad response times!

17 Aug
2 years ago

EliasSoares left a reply on My Token Based Guard For Laravel 5.2

@crowded This package was made focused on Single Page Applications that have API and Front-end running on separate environments, or mobile applications that uses HTTP to access your API, but can't or don't want to use cookies to keep the authentication.

EliasSoares left a reply on PHP Artisan Not Working

@roadrunner89

Try running php artisan -vvv

This will print the full error log. Probably in one of your PHP files you have some wrong syntax. This will show you where to look at.

26 Jul
2 years ago

EliasSoares left a reply on Cleanest Way To Save Model And Relationships

I usually create some helper methods on my controller that do all the logic. On our last project, I extracted all this logic out for a Service class that extends this base ApiService abstract class:

<?php
/**
 * Copyright (c) 2016 IGET Serviços em comunicação digital LTDA - All rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */

namespace App\Services\Contracts;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;

abstract class ApiService
{
    /**
     * @return array
     */
    abstract public function getRelationships();

    /**
     * @return \Illuminate\Database\Eloquent\Model
     */
    abstract public function getModel();

    /**
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Model
     * @throws \Exception
     */
    public function create(array $data)
    {
        \DB::beginTransaction();
        try {
            if (isset($data['relations'])) {
                $relations = $data['relations'];
                unset($data['relations']);
            }

            $created_model = $this->getModel()->create($data);
            if (isset($relations)) {
                $this->updateRelationships($created_model, $relations);
            }

            \DB::commit();

            return $created_model;
        } catch (\Exception $e) {
            \DB::rollback();
            throw $e;
        }
    }

    /**
     * @param array $data
     * @param int   $model_id
     * @return \Illuminate\Database\Eloquent\Model
     * @throws \Exception
     */
    public function update(array $data, $model_id)
    {
        \DB::beginTransaction();
        try {
            $model = $this->getModel()->find($model_id);

            if (isset($data['relations'])) {
                $relations = $data['relations'];
                unset($data['relations']);
            }

            $model->update($data);

            if (isset($relations)) {
                $this->updateRelationships($model, $relations);
            }

            \DB::commit();

            return $model;
        } catch (\Exception $e) {
            \DB::rollback();
            throw $e;
        }
    }

    /**
     * @param \Illuminate\Database\Eloquent\Model $model
     * @param array $data
     */
    private function updateRelationships(Model $model, array $data)
    {
        foreach ($this->getRelationships() as $relationship_name) {
            if (isset($data[$relationship_name])) {
                $relationship_type = get_class($model->$relationship_name());
                switch ($relationship_type) {
                    case BelongsToMany::class:
                        $this->syncBelongsToManyRelationship($model, $relationship_name, $data[$relationship_name]);
                        break;
                    case MorphMany::class:
                    case HasMany::class:
                        $this->syncHasManyRelationship($model, $relationship_name, $data[$relationship_name]);
                        break;
                    default:
                        break;
                }
                unset($data[$relationship_name]);
            }
        }
    }

    /**
     * @param \Illuminate\Database\Eloquent\Model $model
     * @param $relationship_name
     * @param array $data
     */
    private function syncHasManyRelationship(Model $model, $relationship_name, array $data)
    {
        $present_ids = [];
        foreach ($data as $related) {
            $conditions = [
                'id' => array_key_exists('id', $related) ? $related['id'] : null
            ];

            $present_ids[] = $model->$relationship_name()->updateOrCreate($conditions, $related)->id;
        }

        $model->$relationship_name()->whereNotIn('id', $present_ids)->delete();
    }

    /**
     * @param \Illuminate\Database\Eloquent\Model  $model
     * @param string $relationship_name
     * @param array  $data
     * @return mixed
     */
    private function syncBelongsToManyRelationship(Model $model, $relationship_name, array $data)
    {
        return $model->$relationship_name()->sync($data);
    }
}

Here you can see an example service implementation of a model that have a BelongsToMany contacts relationship:

<?php
/**
 * Copyright (c) 2016 IGET Serviços em comunicação digital LTDA - All rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */

namespace App\Services;

use App\Models\Client;
use App\Services\Contracts\ApiService;

class ClientService extends ApiService
{
    /**
     * @return Client
     */
    public function getModel()
    {
        return new Client();
    }

    /**
     * @return array
     */
    public function getRelationships()
    {
        return [
            'contacts',
        ];
    }
}

This code assumes that you will pass model relationship data on a relations key at your request payload.

Then on your controller, you should only do:

    public function store(ClientRequest $request)
    {
        $created_client     = $this->clientService->create($request->all());

    return "your response";
    } 

I know that it feels complicated, but if you give a try, you will see that this speed up your development process and make your controllers very clean!

25 Jul
2 years ago

EliasSoares left a reply on How To Get Last Record Of A Group?

If you have timestamps on your model you can use: $model->latest()

22 Jul
2 years ago

EliasSoares left a reply on SSH To Digital Ocean Only Works For Keys Named "id_rsa"

You need to configure your ssh-agent to use you key.

It defaults to id_rsa...

ssh-add ~/.ssh/id_rsa
```

EliasSoares left a reply on Download Multiple Files

Try using PHP Zip module to generate your ZIP file to dowload...

http://php.net/manual/pt_BR/book.zip.php

EliasSoares left a reply on Updating The User When Attaching A Pivot Element

This happens because you already has loaded the relations and are querying the Collection count, not the Query count.

$user = auth()->user();
$user->books()->attach($book_id);
$user->books->count() // returns 0
$user->books()->count() // returns 1
17 Jul
2 years ago

EliasSoares left a reply on PHPStorm Migration Method Warnings

Same here... never figured out how to solve this. Tell us if you find any solution!

15 Jul
2 years ago

EliasSoares left a reply on Deploy From A Specific Git Tag?

Also you can turn off auto deploy on Envoyer, and use a git hook to trigger the deploy url on tag creation! :)

11 Jul
2 years ago

EliasSoares left a reply on Laravel Scale Network

Very nice topic.

I've started a server migration/splitting for my company applications.

We don't have much traffic yet, but my old server was "all in one". Elasticsearch, mysql, nginx and php.

Now that we are hosting more applications, I want to share the server for a simplified maintenance, but I decided to isolate everything and connect them using DO's private network to connect it.

Is this a good setup? My main idea is: If for some reason I fuck-up with one server, it's easier to fix. Also I think that this will give me more speed on ssd access, since probably each server will use an different drive.

27 Jun
2 years ago

EliasSoares left a reply on Sorting By Associated Model Criteria

Just add a join to your query. Of course it works on Eloquent!

Partner::join(...)->orderBy ('users.email')->get ()

Choose the right join to use, fill the join and cascade all your clauses in this query.

Once you do this, you can do clauses using your related model column.

25 Jun
2 years ago

EliasSoares left a reply on Search Engine On Huge Data In Laravel 5.2

I use ElasticSearch on a 4M cities database, searching by 3 different columns.

That's the best way I found to have a fast and samt typeahead search with results score ordenation (most relevant first).

My response is always bellow 100ms and mean time of 40ms.

At beginning it's hard to understand, but if you have some experience, you take 1 week to learn and implement. It's very robust, running for at least 1 year without downtimes or maintenance.

24 Jun
2 years ago

EliasSoares left a reply on Best Text Editor For Laravel

PhpStorm definetivelly is the better! :)

21 Jun
2 years ago

EliasSoares left a reply on Laravel On Nginx

It runs fine on Nginx. also I think that is the default server for homestead.

17 Jun
3 years ago

EliasSoares left a reply on Need A Solution For A Relationship In Models

manyToMany relationships uses belongsToMany definition on both ways.

:)

EliasSoares left a reply on How To Become Web Development Master?

On front-end, there are many "techniques" that a "master" should know, like SEO, Mobile first development, speed optimization, that you will never stop learning. Also is important to know how to create "human friendly" websites/interfaces understanding how generally a human "reads" the screen, how to keep the attention on the important things, and of course, beautiful designs, follow patterns (own or third-party as material-design guidelines), and create your own development guidelines is important.

Today I consider very important on front end: LESS, Angular, and the use of some tool like Laravel Elixir to compile, minify, parse ECMAScript6, LESS/CSS.

Also is important to know how to build great and organized themes on Wordpress, since if your client need a website that him or him team may update, you theme should run fine on every situation and use all the power of wordpress. (or any other cms that you like, I suggest WP.)

To be a master, focus on making your front-end simple, fast, and reliable. I follow this rules on my developments.

EliasSoares left a reply on How To Become Web Development Master?

First obligation is to practice! Then with practice, never keep a doubt in the mind. Google, read, learn about this question.

Choice to focus first on front-end, understand how to make a pretty website, even you are not an artist, you can just try to copy the style of websites that you looks pretty! Code it on HTML5+CSS. Then learn about using a good css framework like Bootstrap. It saves a lot of time, but I think that should never, ever, be a starting point, since you must understand how CSS and HTML works before use it like a boss.

Then start using Javascript and jQuery (like bootstrap, first learn how do things using javascript, then to to the easy way that is jQuery).

After this, you will be capable to code many layouts and websites using your know how!

If you also decides do become a back-end master, learn about PHP, then PHP Object-oriented, then MySQL. When you are capable to do a simple application using pure PHP, then you are ready to use any framework (like laravel) as a boss. Everything will be easier to understand.

Of course you can skip the basics steps and go to the frameworks directy (bootstrap, jquery, laravel). But on this "easiest" way, you may never understand how the things works, you will need to ask every day on a forum and will never dominate any language.

That's my suggestion, IMHO.

Good Luck!

EliasSoares left a reply on Need A Solution For A Relationship In Models

Yes, define two relationships. Your notification have only one "sender_user" right?

So this is the relationship schema:

1st: Many to Many relationship User belongsToMany Notification (A user has many received notifications) [received_notifications] Notification belongsToMany User (A notification has many recipient) [recipients]

2nd: One to Many relationship Notification belongsTo User (A notification has a sender) [sender] User hasMany Notification (A user has many sent notifications) [sent_notifications]

Since you have two relations with different meanings, you should call they on a suggestive name, as I suggested on square brackets.

14 Jun
3 years ago

EliasSoares left a reply on Radio Button Choice Is Not Being Saved

  • Is gender a fillable attribute?
  • How about your controller? It's filling the model correctly?

Also, why store full "female" or "male", using 6 bytes when you can use only 1 byte by storing "m" or "f"?

In a large dataset this will be critical! :)

EliasSoares left a reply on Sum Paginate

@nicosl

You can make two queries, one for get the aggregate count, another for get the results and paginate.

For get the count, you can do:

  • add your where clauses
  • join the items table
  • sum the items using the sum() method on sql

I'm pretty sure that I have a simillar code that I've wrote anywhere. If I found, i post here.

13 Jun
3 years ago

EliasSoares left a reply on Auth Expiring Early

Maybe a timezone issue?

12 Jun
3 years ago

EliasSoares left a reply on Easy Way, Package?, For Patching Migrations?

You should almost never modify an existent migration. As said, create a new one that correct the problem.

But when working in a dev. version that was not out on production, you can do it since you talk to another developers on your network to mannualy change that on db OR empty/purge database and re run migrations.

If you have really a lot of migrations, may be time to release a brand new version of your software and simplify your tables and migrations, also create a script that migrate from the last release of the old major release to your new major release.

EliasSoares left a reply on Making Laravel Updates Automated?

Don't do this.

Update only when you release a new version. Also is very important have composer.lock file on your git repository. This will guarantee that your production installation will have the same package versions installed, and that everything will work as tested on your development ambient.

Since you release new versions, your dependencies will be updated. If you do not release, and everything is running why update anything?

EliasSoares left a reply on Calculated Fields

@blonkm

So use Cache! Laravel implements many cache drivers that are very easy to use like: Cache::put ('model.434.age', $calculated_age)

Also you have Cache::remember () that allow you passing a callback to define the cache value if not cache yet.

Take a look at docs!

11 Jun
3 years ago

EliasSoares left a reply on Envoyer.io Access Problem Using User Different From Forge

@EmilMoe, I'm sure that the Envoyer Pub key for this project is correctly setup on the user.

The logs shows that Envoyer is trying to login using forge user instead of my new xyz user. I've received a mail from Otwell, I write here the solution if found.

Thanks

10 Jun
3 years ago

EliasSoares left a reply on Envoyer.io Access Problem Using User Different From Forge

I'm not using forge anymore. I added the envoyer ssh key manually by adding it on authorized_keys file on my new user. Same procedure I used to add my dev. Machine ssh key and worked fine.

EliasSoares left a reply on Envoyer.io Access Problem Using User Different From Forge

Looking at /var/log/auth.log i found this:

Jun 10 20:01:01 host-name CRON[2417]: pam_unix(cron:session): session opened for user forge by (uid=0)
Jun 10 20:01:01 host-name CRON[2417]: pam_unix(cron:session): session closed for user forge

Just at the time I request a "Server test" on Envoyer.io. So, envoyer is using the wrong username to access?

EliasSoares left a reply on Envoyer.io Access Problem Using User Different From Forge

@JeffreyWay Could you give some help here? I didn't found any email or contact session at Envoyer.io.

EliasSoares started a new conversation Envoyer.io Access Problem Using User Different From Forge

Hi, I'm setting up a new project on forge, but I'm setting up it with an isolated user, for obvious security reasons.

The problem is that I created the user xyz, added the envoyer's (and my own) public key to authorized_keys file on /home/xyz/.ssh/authorized_keys file.

I can access normally this user on my local machine, no error. But when trying to push, Envoyer.io returns me:

Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).

Looks like for some reason, envoyer is trying to access ssh using a password, but it's disabled and I never typed in any password to forge.

Could someone please give-me some help about this?!

07 Jun
3 years ago

EliasSoares left a reply on Retriving The User(s) Models

@csuares:

This is happening because you are doing an DB query, not an Eloquent Query.

DB::table('users')
                ->whereIn('id', $userIds)
                ->get();

The right way to doing this and getting an collection (not array) of models is doing:

User::whereIn('id', $userIds)->get()

Doing by this way, you do not need to know the table name where users are stored, since User already has this information.

@SaeedPrez:

$collection->toArray() will convert everything to array, including your models.

19 May
3 years ago

EliasSoares left a reply on Where To Find Minor Versions Changelog Of Laravel?

Thanks @ValsiS updated the right answer to the most recent! :)