Models propeties and where are they?

Ste Martin posted 9 months ago

I'm new to Laravel. I am trying to understand if I create a model called Cat, and the cat has a property of Name. I then create a migration that adds the name property and migrate the db.

I now have a property that is only really in a migration file, its not part of the Cat model code. How is someone coming to the code ever to know that this property exists, without migrating a database and looking at the resulting table?

Any one help?


Alberto Rosas replied 9 months ago

In your model you can just add the protected $fillable property needed in case you need to mass assign values.


    namespace App;

    class Cat extends Model {

        protected $fillable = ['name', 'color', 'lives'];


This means that if you want to send the Request from you views to you controller:


    namespace App\Http\Controllers;

    class CatController extends Controller {

        public function store(Request $request) {

            $cat = new Cat();

            $cat->name = $request->input('name');
            $cat->color = $request->input('color');
            $cat->lives = $request->input('lives');


            return redirect()->route('cats.index')
                     ->with('message', 'The cat ' . $cat->name . ' has been created successfully');



So aswering your question, the attributes of the Cat should be in the protected $fillable property.

Good Luck bro!

Ste Martin replied 9 months ago

Thanks for an excellent answer. However fillable would never be a complete list as its only database fields that I want to be editable by request right? so if I could have a property that is legitimately not in that list. And the fillable list does not even hint at what type it should be.

Looking for something more concrete but I don't think its there.

Alberto Rosas replied 9 months ago

Thanks and yes you're right, I guess you can always declare the properties in you model. Good Luck Ste.

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us