Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zachleigh's avatar

Laravel 4 - private and protected in model help needed

I have a model set up to track queries in my site search box. The top bit of the model looks like this:

<?php

class Query extends Eloquent {

    protected $table = 'querys';

    protected $raw_query;
    protected $locale;

    protected $fillable = array('locale', 'raw_query');

And in my Query Controller, I create a Query object like this:

    public function Search() 
    {
        $query = Query::create([
            'raw_query' => Input::get('query'),
            'locale' => substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], ',')),
        ]);

Because both $raw_query and $locale are assigned as protected, I shouldn't be able to access them directly from the Query Controller class, right? However, when I do run this from the Controller class

        echo $query->raw_query;
        $query->raw_query = 4;
        dd($query->raw_query);

raw_query is accessible and changeable without the use of get or set methods. Does Laravel automatically connect the two behind the scenes? Are get and set methods necessary in this case?

0 likes
3 replies
pmall's avatar
pmall
Best Answer
Level 56

You don't have to declare your table columns as model attributes. Remove these two attributes and it will work fine.

As far as I know you can't make them protected. Colums / values pairs are stored in the attributes array of the models and acceded with magic setter / getter.

1 like
zachleigh's avatar

Thanks pmall. That cleared things for me. All appears to be fine now.

JarekTkaczyk's avatar

@zachleigh

@pmall Correct, you shouldn't declare the columns as properties at all. Making them public means that they are updated instead of the attributes array, so in fact nothing will change in the DB.

Making them protected, on the other hand, means that you can use them in the class $this->raw_query and it will affect the property, but not the attribute again, however outside the class, the properties will be never hit.

The latter is sometimes useful, but then you need to follow this:

// in the class
$this->raw_query; // works with the protected property
$this->getAttribute('raw_query') / $this->setAttribute('raw_query'); // works with the column value

// outside the class
$model->raw_query; // ordinary Eloquent behaviour, works with the column value
1 like

Please or to participate in this conversation.