Bacchus's avatar

Laravel Automagic for Beginners?

Hello,

I'm pretty novice and have built some makeshift frameworks before for e-commerce projects, but have never used a mature framework like Laravel outside of exploration. I just finished Laravel 5.7 from Scratch, and I still have a lot of questions about how to wrap my head around all the things Laravel offers me.

For example, when I create a model, I still don't understand why I am able to create a function like:

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

I have not defined hasMany() within the class itself, and it's parent, Model, does not contain a method called hasMany() either. Where does this come from?

Also, there are instances where I seem to call methods as properties and vice versa.

More broadly, is there a condensed reference that isn't the official docs I can chew on to get my head around this API? After finishing the primer, I still don't really know where to reach for what. If the answer is "read the docs", fair enough and I plan to do that too.

Thanks.

0 likes
3 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61

Every model extends Illuminate\Database\Eloquent\Model which has a trait Illuminate\Database\Eloquent\Concerns\HasRelationships which contains hasMany method.

Maybe using IDE like PhpStorm can help you get up to speed with Laravel and it's magic.

There are only few cases important in the beginning like in this case

  • if you call $model->tasks() you will be able to chain on method calls to specify more constraints on your query
  • if you call $model->tasks you will receive a collection of results for your query
  • if you have scopeBest() method on your model you can call it like $model->best()

That will get you far from where you are now. When you get past that you can ask for more info on Laravel magic.

Bacchus's avatar

I have student access to PhpStorm until December. I'll download it. Thanks for the great tips!

Do you think that going through and reading the documentation has value for someone at my stage of learning, or should it be used mainly as a reference for specific issues?

bugsysha's avatar

Do you think that going through and reading the documentation has value for someone at my stage of learning, or should it be used mainly as a reference for specific issues?

I've never learned anything from documentation. Docs are important to understand but not a source for learning at least for me.

Easiest way for me to learn Laravel was to start using it. Either rewrite some web app with Laravel or something that you wanted to build for a long time. Also following some video guide might come in handy. All of those approaches are like jumping into fire. So like Nike says "Just Do It" 🤞🏻

1 like

Please or to participate in this conversation.