laravel model attributes code example

Example 1: laravel create model

# The easiest way to create a model instance is using the 
# make:model Artisan command:

php artisan make:model Flight

# If you would like to generate a database migration when you 
# generate the model, you may use the --migration or -m option:

php artisan make:model Flight --migration
php artisan make:model Flight -m

Example 2: laravel add attribute to model

$user = User::find(1);

// add occupation to user instance
$user->setAttribute('occupation', 'Web Developer');

Example 3: $this- attribute laravel

To define a mutator, define a setFooAttribute method on your model where Foo
  is the "studly" cased name of the column you wish to access. So, again,
lets define a mutator for the first_name attribute. This mutator will
be automatically called when we attempt to set the value of the first_name
attribute on the model:

class User extends Model
{
    public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = strtolower($value);
    }
}

Example 4: laravel eloquent json type

<?php
//Array & JSON Casting
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'options' => 'array',
    ];
}
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'options' => 'array',
    ];
}

Example 5: laravel dynamic attributes

class User extends Eloquent {


    public function getFullNameAttribute()
    {
        return $this->first_name.' '.$this->last_name;
    }
}

Example 6: laravel dynamic attributes

$user = User::find(1);
$user->full_name;