JuanRangel

JuanRangel

Member Since 3 Years Ago

Experience Points 27,440
Experience
Level
Lessons Completed 326
Lessons
Completed
Best Reply Awards 2
Best Answer
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.

09 Nov
1 week ago

JuanRangel left a reply on Do We Have A Mobile App?

@brybc04 Not everyone is like that guy. Welcome to the forums!

JuanRangel left a reply on Do We Have A Mobile App?

@CRONIX - Lynda, Linkedin Learning, Udemy, and team treehouse all have apps. Seemed like a legitimate question to me...No need to be a smart ass.

08 Nov
1 week ago

JuanRangel left a reply on Please Bring Back The Older Laracasts Design

After listening to the Laravel Snippet I thought this was a troll post.. LOL

09 Oct
1 month ago

JuanRangel left a reply on Bloated User Model

@D9705996 Thanks again for your help. I was able to use the scenario above and it worked out great.

JuanRangel left a reply on Bloated User Model

I leaning towards creating a Report class so I can do something like

$user->reporting()->topPerformers()

I also have similar methods for a Group model. So getting the top-performing groups would look something like.

$group->reporting()->topPerfomers()

I'll create a UserReporting and a GroupReporting for each model.

app\User.php

class User
{
    public function reporting()
    {
        return new UserReporting($this);
    }
}

app\Group.php

class Group
{
    public function reporting()
    {
        return new GroupReporting($this);
    }
}

Going to see how this works out.

JuanRangel left a reply on Bloated User Model

@D9705996 I remember seeing that video a year or so ago. I forgot about it. Thanks for the help. Viewing the video now.

JuanRangel started a new conversation Bloated User Model

Hello, I am trying to figure out the best place to place code that is responsible for reporting purposes. For example, I have a User class that can get the top/bottom performers. It's a simple way to get the users with the most conversations in the system, so the user with the most conversations are at the top of the scopeTopPerformers method. My user model is starting to get really bloated with a lot of these methods that are used just for reporting to the admin area.

What is the best practice for handling these kinds of methods/functions?

18 Sep
2 months ago

JuanRangel left a reply on Creating Model Record In Multiple Locations

Thanks, @PricelessRabbit I've implemented this in my codebase. I appreciate the help.

17 Sep
2 months ago

JuanRangel left a reply on Creating Model Record In Multiple Locations

@PricelessRabbit Ah, that's actually a great idea. I hadn't thought of that. I have not used a service like this before. Can you share an example?

JuanRangel started a new conversation Creating Model Record In Multiple Locations

I am using a ConsultationController to create a Consultation record. I now want to be able to create a consultation record in my RegisterController. What is the best way to handle this?

A few options that come to mind:

  1. Add a method on the User model to handle this. $user->startConsultation()
  2. Use the Consultation::create() in all locations.

What is the best practice here? Which class should have the responsibility of creating a consultation?

24 Aug
2 months ago

JuanRangel left a reply on How To Read Nested Array, Obj, Items?

Is it returning a collection or just an array of objects?

14 Aug
3 months ago

JuanRangel left a reply on Laravel Stop Queue Job If Exception Is Thown

Just make sure in your first try catch that you return.

i.e

public function handle()
{

       try {
          //STEP 1 tasks
       } catch (\Exception $e) {
           Log::error('Error message: '.$e);
       return false;
       }

       try {
      // will not execute
          //STEP 2 tasks
       } catch (\Exception $e) {
           Log::error('Error message: '.$e);
       }

}
13 Aug
3 months ago

JuanRangel left a reply on Eloquent: API Resources

The JsonResource class has a withResponse method.

/**
     * Customize the outgoing response for the resource.
     *
     * @param  \Illuminate\Http\Request
     * @param  \Illuminate\Http\Response
     * @return void
     */
    public function withResponse($request, $response)
    {
        $response->header('X-Value', 'True');
    }

https://laravel.com/docs/5.6/eloquent-resources#resource-responses

JuanRangel left a reply on Application Environment For Local Or Production

I would not keep it at local...

When the env is set to local it has an impact on your logging, error reports, and migrations. That is just what I can think of at the top of my head. I am sure it impacts other things as well.

JuanRangel left a reply on How To Addition A Column With Eloquent?

@alihoushyaripour

You cannot chain an increment and update call together. You can do what @tykus suggested or pass the update values into the increment values third agrugment... This works.

User::find($userId)->increment('rate', 1, [
    'active' => true,
    'updated_at' => $date
]);

JuanRangel left a reply on How To Addition A Column With Eloquent?

Try User::find($userId)->increment('rate')

27 Jul
3 months ago

JuanRangel left a reply on Configure Artisan Console Error Colors?

Thank you @angeloj. I just changed the ANSI colors in phpstorm and this fixed my issue.

25 Jul
3 months ago

JuanRangel left a reply on Reuse Query

Dammit. Sorry for this post just found a solution.. Cloning the query before filtering it worked for me. https://laracasts.com/discuss/channels/eloquent/reusing-query-with-extra-where-condition?page=1

JuanRangel started a new conversation Reuse Query

I've created this simple query. $models = Model::whereBetween('created_at', [$start, $end])

and I am trying to use it for several things. For example, I am getting the total count with $models->count() // 20 and the total amount with $models->sum('amount') // 50

I am then trying to filter the query for each date in an array and this is where I am having problems.

Running this query $models->whereDate('created_at', '2018-07-24')->get() returns all records for this day correctly but if I try to run another query for example $models->whereDate('created_at', '2018-07-25')->get() I get 0. It seems like I am modifying the initial query and once modified I am unable to use the $models variable for anything else as it now holds all of the data from the $models->whereDate('created_at', '2018-07-24')->get() query.

What am I doing wrong? Can someone explain how I can use the initial query several times?

06 Jul
4 months ago

JuanRangel left a reply on Return Eloquent Collection From Relationship Method

@bobbybouwmann @staudenmeir

Actually, nevermind. That did not work. Right now I am getting instance of Illuminate\Support\Collection I need to return an Illuminate\Database\Eloquent\Collection.

My intended use is to be able to grab all the consultations that belong to the practice through the members(User::class). I am creating a reports dashboard and need to be able to run a query between dates or on specific date.

$practice->consultations::whereDate('created_at', $date)->get();

This does not work with a Illuminate\Support\Collection.

JuanRangel left a reply on Return Eloquent Collection From Relationship Method

@staudenmeir Thank you! That worked!

@bobbybouwmann

I was trying to pull in the collections off of the members relationship for all members. What @staudenmeir suggested above worked! Thanks for commenting.

JuanRangel started a new conversation Return Eloquent Collection From Relationship Method

So I have a case where a user can have a consultation relationship with two possible columns. I had to create three methods to get both cases and that looks like this...

public function consultations()
    {
        return $this->initiatedConsultations->merge($this->recipientConsultations);
    }

    public function initiatedConsultations()
    {
        return $this->hasMany(Consultation::class, 'participant_1');
    }

    public function recipientConsultations()
    {
        return $this->hasMany(Consultation::class, 'participant_2');
    }

This works fine and returns an eloquent collection of all consultations of a user. I have a Practice model that has a members() method that pulls all the users that belong to a practice.

public function members()
    {
        return $this->belongsToMany(User::class);
    }

I need to grab all of the consultations for the practice and I can do that with this method

$consultations = collect();
        $this->members->each(function ($m) use ($consultations) {
            $consultations[] = $m->consultations();
        });
return $consultations->flatten();

Is there a way to pull in the relationship as an eloquent collection?

06 Jun
5 months ago

JuanRangel left a reply on Getting Only Relatioship Collection

That's exactly what I'm trying to do. Thanks

JuanRangel left a reply on Getting Only Relatioship Collection

@Cronix Thanks for the quick reply. I am only trying to query the patients. Running the code above I get the member with the patients. Is it possible to only query the patients?

I can do this using this method.

$patients = collect();

        foreach($this->members as $member) {
            $patients->push($member->patients);
        }

        return $patients->flatten();

but I want to be able to order and paginate like an eloquent query.

JuanRangel started a new conversation Getting Only Relatioship Collection

So I am trying to retrieve all the patients for a practice. I can see the patients with this $practice->members()->with('patients')->get() Each member has their own list of patients. Is it possible to only query the patients? I need to be able to run queries on the patients. Something like $practice->members->patients->where('first_name', 'John')->first() would be perfect.

Is this possible?

19 Feb
9 months ago

JuanRangel left a reply on Looking For Experience Professional To Discuss Large Application Structure

@jlrdw Not that big. Right now it has around 20k records. I'm more looking for someone to help me get a handle on the complexity. Routes, controllers, ,models, etc..

JuanRangel started a new conversation Looking For Experience Professional To Discuss Large Application Structure

Hello,

I have a client's site running on Laravel and I'm looking for someone with more experience than I, to get feedback from. Instead of posting all my questions here, I'd rather hire someone that can spend an hour or two going over the project and answering my question over a call/skype. This was really my first big application built with Laravel so there are some things that I want to clean up and optimize to make it easier for me to maintain. I need someone with experience working on a large project. Questions include invite system refactoring, model relations, and database structure.

The app has almost 100% test coverage is hosted on GitHub and is integrated with Forge, Envoyer, BugSnag, and MailGun.

Please post your rate and experience if you're interested.

09 Feb
9 months ago

JuanRangel left a reply on Required If Coupon != 0

I ended up going with this:

$coupon  = Coupon::where('code', request()->coupon)->first();
        $billing = [];

        if ('p' !== $coupon->type && 100 !== $coupon->amount) {
            $billing = [
                'stripeToken'     => 'required',
                'card_name'       => 'required',
                'billing_address' => 'required',
                'billing_city'    => 'required',
                'billing_state'   => 'required',
                'billing_zip'     => 'required',
                'billing_country' => 'required',
            ];
        }

        return array_merge([
            'first_name' => 'required',
            'last_name'  => 'required',
            'company'    => 'required',
            'email'      => 'required',
            'phone'      => 'required',
            'city'       => 'required',
            'state'      => 'required',
            'zipcode'    => 'required',
            'country'    => 'required',
            'coupon'     => 'exists:coupons,code'
        ], $billing);

    }

It feels a bit sloppy, but it works.

JuanRangel started a new conversation Required If Coupon != 0

I am trying to validate billing fields only if the coupon does not equal zero. So if after a coupon is applied, the price is 0, I don't want to require the billing fields.

$rules =  [
            'first_name'      => 'required',
            'last_name'       => 'required',
            'company'         => 'required',
            'email'           => 'required',
            'phone'           => 'required',
            'city'            => 'required',
            'state'           => 'required',
            'zipcode'         => 'required',
            'country'         => 'required',
            'stripeToken'     => 'required',
            'card_name'       => 'required',
            'billing_address' => 'required',
            'billing_city'    => 'required',
            'billing_state'   => 'required',
            'billing_zip'     => 'required',
            'billing_country' => 'required',
            'coupon'          => 'exists:coupons,code'
        ];

I basically want do a simple check if('fixed' == $coupon->type && '100' == $coupon->amount) don't require the billing fields, if the coupon > 0 then require the billing fields. Anybody know how I could accomplish this?

05 Feb
9 months ago

JuanRangel left a reply on Multiple OrWhere Calls

@Nash I actually did do something like that. This is what I went with.

$daysOld = [];
for ($i = 3; $i <= 50; $i += 3) {
    $daysOld[] = Carbon::now()->subDays($i);
}

Thanks for you help.

JuanRangel left a reply on Multiple OrWhere Calls

Thank you Nash. I was able to clean it up quite a bit with this.

$day3  = Carbon::now()->subDays(3);
$day6  = Carbon::now()->subDays(6);
$day9  = Carbon::now()->subDays(9);
$day12 = Carbon::now()->subDays(12);

$facilitators = Facilitator::whereIn('starting_at', [$day3, $day6, $day9, $day12])->get();

JuanRangel started a new conversation Multiple OrWhere Calls

Every 3 days I need to fire off an email. I am grabbing courses that started 3, 6, 9, and 12 days ago. This query works, but is it possible to clean it up?

Course::where('class_start_date', Carbon::now()->subDays(3))
                         ->orWhere('class_start_date', Carbon::now()->subDays(6))
                         ->orWhere('class_start_date', Carbon::now()->subDays(9))
                         ->orWhere('class_start_date', Carbon::now()->subDays(12))
                         ->get();
15 Jan
10 months ago

JuanRangel started a new conversation Help Figuring Out The Proper Relationship

I have three tables.

exercises

  • id

invites

  • invitable_id == exercise->id
  • invitable_type == App\Exercise

storytellers -storytellerable_id == exercise->id -storytellerable_type == App\Exercise

I need to be able to grab storyteller's invite($storyteller->invite) or a storyteller that belongs to an invite($invite->storyteller).

I cannot wrap my head around how to make this work. Can someone help me out?

20 Nov
1 year ago

JuanRangel left a reply on How To Mock A User With A Cashier/Stripe Subscription?

Where are you getting your $token variable from? I am trying to test subscriptions in my app and I hit a wall for several hours now..

02 Oct
1 year ago

JuanRangel started a new conversation Deleting Images That Belong To A Message

I have an app where I want to delete the images attached to a message that is attached to a thread. So I have a threads, messages, images, and image_message tables. I set foreign keys up to cascade so when a thread is deleted, then the messages are deleted and when the messages are deleted then the images(records) are deleted. How can I delete the image_message record when the image is deleted?

Basically, when a thread is deleted I want to chain down and delete all the records that are part of that thread. Thread > messages > image_message.

31 Aug
1 year ago

JuanRangel started a new conversation Failed To Mount Component

Morning Guys,

I came back to laravel project that I have not touched for a few months and I cannot get vue to work. When I load a page that uses a component I am getting the error Failed to mount component: template or render function not defined. I made sure to run npm install, I've deleted my node_modules folder and ran it again, I've made sure I am requiring laravel-elixir-vue-2, also tried to load different flavors of vue(standalone and runtime only).

This is how I am loading vue in my bootstrap.js file

window.Vue = require('vue');
require('vue-resource');

Anyone have an idea on why I can't load a component?

20 Jul
1 year ago

JuanRangel left a reply on Cleaner Auth::attempts

Thanks. That gets rid of all the else statements.

JuanRangel started a new conversation Cleaner Auth::attempts

I am tried to check for multiple issues when a user logs in. 1. I want to make sure the credentials are in the db, 2. Check if the user is disabled, 3. Check if the user has an active account. The code below works fine, it just looks a bit sloppy to me. Any refactoring to clean this up a bit?

 public function login()
    {
        $email    = request()->email;
        $password = request()->password;
        $remember = request()->remember;

        if (Auth::attempt(request(['email', 'password']), $remember, false)) { // check if use is in database
            if ( Auth::attempt(['email' => $email, 'password' => $password, 'disabled' => 0], $remember, false)) { // checks if user is disabled
                if (Auth::attempt(['email' => $email, 'password' => $password, 'verified' => 1])) { // checks that user has been verified
                    return redirect('/dashboard');
                } else {
                    return redirect('/login')->withErrors([
                        'email' => 'Your account is not active.'
                    ]);
                }
            } else {
                return redirect('/login')->withErrors([
                    'email' => 'Your account is disabled.'
                ]);
            }
        } else {
            return redirect('/login')->withErrors([
                'email' => 'These credentials do not match our records. Please try again.'
            ]);
        }
    }
12 Jul
1 year ago

JuanRangel left a reply on Laravel Mix Can't Find App.js

Thanks. I found that page right after posting this question. Running npm i --save-dev babel-loader sass-loader vue-loader worked for me. Now I'm running into this issue

Failed to mount component: template or render function not defined.

The search continues for that one.

JuanRangel started a new conversation Laravel Mix Can't Find App.js

So I've been working on this project for 8 weeks now and just about done. I've been usingnpm run watch while I work because I am using a lot of vue. So I tried to run npm run production and received an error. I can't remember the error now, it's been a few hours. So after that error I tried to run npm run watch again, no luck. I started receiving errors no matter what script I tried to run. The main error is this.

npm ERR! code ELIFECYCLE
npm ERR! errno 2

When I run npm run watch I now get this error

This dependency was not found:

* /Users/juan/Code/laravel/rbse/resources/assets/js/app.js in multi ./resources/assets/js/app.js

But the file is there. I stripped everything out of my webpack.mix.js file and just kept this like in there mix.js('./resources/assets/js/app.js', 'public/js');, but not luck. I tried different variation, but I cannot get mix to locate the file. I've also deleted my package.json file and replaced it with the current version on github, deleted the node_modules directory and re-ran npm install, I've also tried yarn install, and a combination of other things that I have found online while searching. Anybody had this issue before? Any idea on how to fix it?

20 May
1 year ago

JuanRangel started a new conversation Nested Laravel Applications

I'm trying to build a personal application that allows me to host other projects within my site. I want to basically host other files in a directory and access those files with a structure like http://myapp.com/dev/nested-project The project can be either larval, WordPress or vanilla PHP, css,js, etc... I set up the route that handles the request, but I am not sure how to render the directory content. Any idea how this would work?

13 Dec
1 year ago

JuanRangel left a reply on Profiles Table Vs User Meta Table

Ok. Thank you! Going to go this route then.

JuanRangel left a reply on Profiles Table Vs User Meta Table

Hey vogtdominik, thank you for your reply. I am sorry that I wasn't more clear on my current setup. Right now I have a single users table for all users. I then have a roles table that has different roles i.e administrator, teacher, student. I then have a pivot table that connects a role to a user called role_user I also have a profile table that connects to a user profile_user. I definitely like specifying the columns that I want, and rather that then having key value pairs. I am just not sure of the drawbacks.

So you would recommend a profile table with all possible fields as a column?

JuanRangel started a new conversation Profiles Table Vs User Meta Table

I can't make my mind up about this. I have users with different roles. Some are teachers and some are students. What is better? A profile table with all possible attributes as nullable columns or a user meta table that stores each key => value as a new row?

The fields will change depending on the user role so all students will have a grade field and all teachers will have a school field, but a teach will never have a grade field. We may add additional fields in the future, so I'm trying to determine the best solution for this.

Does anyone have experience with something like this?

12 Dec
1 year ago

JuanRangel left a reply on FatalThrowableError When Passing Argument To Notify() Constructor (5.3)

Try

public function __construct(LoginToken $loginToken)
    {
        $this->loginToken = $loginToken;
    }

JuanRangel started a new conversation Schedule Deletion

I am attempting to schedule a model record for deletion after 48 hours. So I have a boolean column on a Conversation model. When I close the conversation I set the is_closed column to 1. What would be the best to way to delete this record from the db in 48 hours?

03 Dec
1 year ago

JuanRangel left a reply on Eager Loading Using Multiple Tables

What is the error you are getting?

JuanRangel left a reply on Disable Automatic Login After Registration

I threw your register method in my RegisterController and it worked fine. When I register a new user I am redirected to the login page. What are you getting?