Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a NotMapped entity in Laravel Model?

I am novice in laravel, therefor my question may be odd to someone. Well, my question is how can I write a entity in Laravel Model class which will not be created any field in database after my migration. For example

class JobseekerModel extends Model
{
    use SoftDeletes;
    protected $table='dbl_jobseekers';
    protected $primaryKey='id';
    protected $fillable=[
        'FirstName',
        'MiddleName',
        'LastName',
        'Dob',
        'Education',
        'DesireField',
        'Skill',
        'SpecialSkill',
        'Experience',
        'Location',
        'HomeAddress',
        'Salary',
        'Comenteries',
        'Resume'
    ];
    protected $dates = ['deleted_at'];
}

This is my Model, now I want to add another property named 'PagedListSize' in my Model, however I don't like to create it as a database column. So how do I do this?

For example I am acquainted to use NotMapped property in .Net Framework, which is written like

[NotMapped]
public int PagedListSize {set; get;}

So, how do I able to do this. Is there any way to do this in laravel? i am working on Laravel 5.4

like image 572
gdmanandamohon Avatar asked May 06 '17 11:05

gdmanandamohon


3 Answers

You can create custom Mutators to have that kind of custom properties wihout mapping them to database fields in Laravel.

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

    public function setFullNameAttribute($value)
    {
        list($this->first_name, $this->last_name) = explode(' ', $value);
    }
}

and then you can use it like this after you initialize the model:

$tag->full_name = "Christos Lytras";
echo $tag->first_name; // prints "Christos"
echo $tag->last_name; // prints "Lytras"

Here is a tinker screenshot:

Artisan Tinker Example

like image 159
Christos Lytras Avatar answered Nov 11 '22 00:11

Christos Lytras


The best way to do this in Laravel indeed is through custom Mutators. In addition, mutators can be configured to be displayed in the json or array output dump of the model. e.g. for PagedListSize we could have:

public functionGetPagedListSizeAttribute()
{
    return #some evaluation;
}

protected $appends = array('pagedListSize');

This way, pagedListSize will not only be available directly as a field but also be available whenever the model is serialized as Json or Array.

like image 35
Chibueze Opata Avatar answered Nov 10 '22 23:11

Chibueze Opata


You can add protected properties to Laravel Model, it's fine as long as they do not collide with field-names. Besides, with Laravel, migration are deciding of DB structures, not models, so you do not take the risk to create fields automatically (actually, default models works with no properties out of the box).

EDIT : Example from the default package User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
    * You can add some properties here
    * will require getter and/or setters
    * does not need to be fillable
    */
    protected $someLogicalProperty;

}

The actual db structure is defined in the migration (2014_10_12_000000_create_users_table.php) :

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

As you can see, timestamps and token are not even listed in the user model. All the fillable when defined will be setable as public property on the user object ($user->name = 'Bob';, but you can also pass it as argument to the create()/save() inherited methods). Entities are not directly accessed in Laravel, but there are here and can be further specified if needed.

like image 29
fab2s Avatar answered Nov 11 '22 00:11

fab2s