How to make none-database model two attributes in Laravel

Viewed 202

I'm a newbie in Laravel. Please guide me.

Port is a Model and Coordinates is a none database Model. There are 2 floats (lat and long) in the Port Model. When a Port is loaded from the database, the 2 floats are cast to a Coordinates object.

My first question is, how do I make a non-database model with two attributes?

My second question is, how do I make a cast 2 floats in Port Model with Coordinates object?

Here is my Code Coordinates Model none-database Model with two attributes

class Coordinates extends Model
{

//Add attribute
protected $attributes = ['latitude', 'longitude'];
}

and here is Port Model With

class Port extends Contracts\AppModel
 {
    protected $coordinates = Coordinates::class;

    protected $fillable=[
        'un_latitude',
        'un_longitude',
    ];

    function __construct(array $attributes = array())
    {
         $this->coordinates = Coordinates::class;
         $this->coordinates->latitude = $attributes["un_latitude"];
         $this->coordinates->longitude = $attributes["un_longitude"];
    }

}
1 Answers

Every Eloquent model is supposed to be linked to one table in a database, as far as I understand. Rather just add latitude and longitude as columns in your migration to create the port table.

Related