chadhutchins

chadhutchins

Member Since 6 Months Ago

Experience Points
3,490
Total
Experience

1,510 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
30
Lessons
Completed
Best Reply Awards
0
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 1
3,490 XP
Jul
23
2 months ago
Jul
22
2 months ago
Activity icon

Started a new conversation Is It Possible To Create Object From Array Value And Chain A Method Call?

Hello, I was hoping to do something like this, but I'm receiving the following error "unexpected T_OBJECT_OPERATOR"

$a = ["class" => "App\Thing"];

$result = $a["class"]()->myMethod();

Is this possible? Or do I have to do it with two lines like so

$a = ["class" => "App\Thing"];

$obj = $a["class"]();
$result = $obj->myMethod();

Thanks!

May
24
4 months ago
Activity icon

Replied to Model Accessors Not Available In The Resource

I figured this one out... I have a few levels of abstraction. I have my Base Model, an abstract model that extends the Base, and more models that extend the abstract model.

I was sending an instance of the Base Model to the Resource, but my accessors live on the abstract model or above. So after sending an instance of the other models to the Resource, I could then see the accessor data.

Solved!

Activity icon

Started a new conversation Model Accessors Not Available In The Resource

Hi all, I'm using resources to transform my models. However I've noticed that my model's accessors all return null in the Resource.

Is it possible to get the data from my accessors when inside my Resource toArray() method?

When in the toArray() method $this seems to be the Resource and not the Model.

Any ideas? Thanks!

May
22
4 months ago
Activity icon

Started a new conversation How To Cast A Model To Different Model Based On Field

Ex. I have a main Food Model. Then I have abstract classes Fruit, Meat, etc. I also have more specific classes that extend the abstract classes. Ex. Ribeye extends Meat, Apple extends Fruit.

My foods table looks something this: (sorry for the formatting, markdown for tables doesn't seem to work)

id class name ext1 ext2 ext3

1 App\Fruits\Apple apple 5 10 3

2 App\Meats\Ribeye meat 10 10 1

3 App\Meats\Filet meat 8 7 10

Where ext1, ext2, ext3 mean different things for each model.

There are cases in my app where all I have is a food id. So currently I have to do something like this to ultimately return the correct model:

$food = App\Food::find($id);
$food = $food->class::find($id);

I'm guessing this does two separate queries even though it's the same underlying data (not sure on that). But either way it doesn't feel right.

Is there a why to cast the first $food variable to the correct class? Or maybe there's a chain call to cast to another class?

Need something like:

$food = App\Food::find($id)->cast($this->class);

Other option would be to break out the Food types into different tables, but I want to stay away from that if possible.

Thoughts? Thanks!

May
20
4 months ago
Activity icon

Replied to Adding Same Accessor Method To Multiple Model Classes

@snapey thanks again for the help! I thought I tried adding that to a trait before and had issues, but I guess not. I did what you suggested and that worked perfectly. Thanks!

Activity icon

Replied to Adding Same Accessor Method To Multiple Model Classes

@snapey Thanks, I think that's the best answer right now, I was just hoping to avoid copy/paste the same accessor in multiple models. Would be nice if this could be done through a trait somehow.

Thanks again for the help!

May
17
5 months ago
Activity icon

Replied to Adding Same Accessor Method To Multiple Model Classes

@snapey thanks for the feedback, felt like overkill extending a model for this. Traits felt just right, but I couldn't get it right.

Here's what I tried:


namespace App\Traits;

trait Detailable
{
    public function getAttribute($key)
    {
        if ($key == 'details') return $this->details;
    }

    public function setAttribute($key, $value)
    {
        // don't really care about the setAttribute... 
        return parent::setAttribute($key, $value);
    }
}

Basically if the key is 'details', return the protected member variable. It would always return null for me. Any ideas?

Activity icon

Started a new conversation Adding Same Accessor Method To Multiple Model Classes

Hi all, I'm looking to add the same accessor to multiple models. I looked at Traits, but I don't think it quite solves the problem. Here's an example:

class User extends Model
{
    protected $details = [
        'a' => 1,
        'b' => 2,
        'c' => 3,
    ];

    public function getDetailsAttribute() {
        return $this->details;
    }
}

I want to add this same details accessor to multiple models WITHOUT having to copy/paste the getDetailsAttribute in each model class.

Is there a way to do this?

Thanks!

Activity icon

Replied to How To Add Calculated Fields To An Eloquent Resource?

Thanks for the advice. That makes sense. I was overthinking this one...

What's the best way to handle this in the model?

Should I use the $appends option where it will always calculate that property when the model is loaded?

Or maybe have a model method I can call whenever I need to calculate it?

Any thoughts around this? Thanks!

May
16
5 months ago
Activity icon

Started a new conversation How To Add Calculated Fields To An Eloquent Resource?

I have an api call, something like GET /api/users/1. This returns a User. I have a UserResource that defines what data is returned.

I want to return an isVIP boolean that says if this user is a MVP or not. This is based on data related to the User. Ex. A User is an MVP if they have an active subscription, they have multiple orders and have been around for more than a year.

Should the logic for this exist in the UserApiController? Or do I make the checks in the UserResource?

In some cases the UserApiController method will already have all of the information needed to determine if the user is an MVP, so it seems inefficient sometimes to put the logic in the UserResource.

Is there a way where you can set a list of extra methods to run on the resource? (Sort of how you can use Factory States to set specific data for a record)

It's like I need to do something like this:

return new UserCollection($user)->apply('isMVP'); 
return new UserResource($user)->apply('isMVP'); 

Does anything like this exist? Is there a recommended way to do this?

It looks like another option may be to do it in the UserModel and use the $appends property. Is this a better way to do it?

Thanks!

May
08
5 months ago
Activity icon

Started a new conversation Determining If Multi-level Relationship Records Exist

Hello, I have 3 models: Users, Movies, Shows

Users can have many Movies and Shows. Movies and Shows can only have one User.

What's the best way to determine if given a Movie record, if the related User has any Shows?

I've found a couple ways that work, but they just don't feel like the right way for some reason:

// in this flow, I already have a $movie
// you can assume $movie was passed in, but it's a App\Movie object
// the same result you'd get from something below
$movie = App\Movie::find(1);

Method 1:

$movie->load('user.shows');
if ($movie->user->shows->isEmpty()) { 
   /* no shows */ 
} else {
   /* has shows */ 
}

Issue here is if you do the if check on $movie->user->shows and there are no shows, it's going to throw a PHP notice that there's no "shows" member variable, so you'd first have to check if that exists.

Method 2:

// even though I already have $movie, I could do another lookup
$movie = App\Movie::has('user.shows')->where('id',$movie->id)->get();

if ($movie->isEmpty()) { 
   /* no shows */ 
} else { 
   /* has shows */ 
}

What's the best to do this. Thanks!

Apr
17
6 months ago
Activity icon

Started a new conversation Looking For A Pattern For Managing Similar Objects Of Different Types

For example, say I have an app that generates html forms. I have a Model for my Fields that can be on a Form. The Fields model has the following fields on the table: id, name, type, ext1, ext2, ext3.

The type values could be "text", "dropdown" or "textarea".

Based on the type, the ext1, ext2 and ext3 fields mean different things. For a type=text Field, ext1 might be the length of the text field. For a type=dropdown Field ext1 might contain a comma separated string of the dropdown values to be displayed.

What are some suggested PHP Patterns for loading up these Fields of different types and for them to have their own functionality (for rendering, saving, etc.)? Or is there a better approach other than having the ext1, ext2 and ext3 fields?

I may be over complicating this, I just want to make sure I start down the right path. Based on the php pattern series (https://laracasts.com/series/design-patterns-in-php) I'm thinking a combination of the Template Method and Adapter Patterns is what I need.

Thoughts? Thanks!

Mar
21
6 months ago
Activity icon

Replied to How To Structure Controller For AJAX And CRUD Endpoints?

@CRONIX - I did see the comment there and tried to add that to the global axios header and manually doing it in my individual axios call, but it still would not get inside the wantsJson() if statement.

Any ideas why that still wouldn't work? wantsJson is much more readable than isXmlHttpRequest.

Activity icon

Replied to How To Structure Controller For AJAX And CRUD Endpoints?

@ARTCORE - Switching from

$request->wantsJson()

to

$request->isXmlHttpRequest()

did indeed work.

Thanks!

Activity icon

Replied to How To Structure Controller For AJAX And CRUD Endpoints?

@CRONIX - Makes sense. Thanks for the wantsJson() tip. However I'm not able to get inside that if statement.

Here's my ajax call:

axios.get('/cars').then(response => {
    console.log(response);
});

And here's my controller:

public function index(Request $request)
{
    $cars = Car::all();
    
    if ($request->wantsJson())
    {
        return $cars;
    }

    return view('cars.index',['cars'=>$cars]);
}

Also, the axios default request header is setup:

window.axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest' };

What am I missing?

Activity icon

Started a new conversation How To Structure Controller For AJAX And CRUD Endpoints?

We have a pretty standard Laravel app. I have the usual CRUD endpoints for the for dealing with my models, but I also need to add some AJAX calls.

Say I have a CarsController. Is it pretty typical to have my CRUD endpoints there AND any of the AJAX call endpoints I would need? Or is it better organized to have those in two different Controllers?

Similarly, I have an endpoint to list all Cars and it spits out a view with a nice table to show me all of my Cars. I need to have an AJAX endpoint that gives me an array of all cars in JSON but not render a view. Should this call a single Controller endpoint (as they do the same thing except the render part) or should it be split into to Controller methods?

Thanks!