Skeletor
Skeletor

Reputation: 3413

How to use a customized/restrained table for a model in laravel?

Let's say I have two models 'Car' and 'Domestic' that use the same table named 'cars'. As example:

cars
id | brand | type
0  | bmw   | foreign
1  | audi  | domestic
2  | ford  | domestic

The 'Car' model uses the whole 'cars' table as it is. But when I call the 'Domestic' model then only the rows that have the 'type' column set to 'domestic' will be used and affected. So that when I do:

$cars = Car::all(); // returns all cars

$domestics = Domestic::all(); // returns domestic cars

Domestic::create(['brand'=>'fiat']); // creates a car with domestic type

We can customize the table name for the model with protected $table = 'cars'. Is there a way to restrain the custom table?

Upvotes: 1

Views: 96

Answers (2)

I dont believe you can restrain eloquent model how you would like it, but as a workaround you can try this method overrides:

In your Domestic.php add this methods:

public static function all()
{
    $columns = is_array($columns) ? $columns : func_get_args();

    $instance = new static;

    return $instance->newQuery()->where('type' => 'domestic')->get($columns);
}

public static function create(array $attributes = [])
{
    $attributes = array('type' => 'domestic') + $attributes;

    return parent::create($attributes);
}

But it is kind of dirty solution and i dont really like it. In your case i would make scope for domestic cars in your Cars model:

public function scopeDomestic($query){

    return $query->where('type', '=', 'domestic');

}

then i would query all domestic cars like this:

Cars::domestic()->get();

as for storing new domestic cars entries, i would add following static class in your Car model:

public static function createDomestic($attributes){

    return Cars::create(['type' => 'domestic'] + $attributes);

}    

And i would store new domestic cars like this:

Cars::createDomestic(['brand'=>'fiat']);

Then delete Domestic model you created, its no longer needed :-)

Upvotes: 1

Komal
Komal

Reputation: 2736

Hope this helps you..

$cars = Car::all(); // returns all cars

$domestics = Domestic::where('type', 'domestic')->get(); // returns domestic cars

Upvotes: 1

Related Questions