Can I use call table view with the model in laravel? What good practice is it? or is it preferable to call it with the DB selector?
Example = vusers / Model: User
Can I use call table view with the model in laravel? What good practice is it? or is it preferable to call it with the DB selector?
Example = vusers / Model: User
More than good bad / practice would say that it is a design decision in the architecture of the application, laravel (eloquent) will treat the view as a table.
Special consideration must be given to how to arm the view to allow updates
e inserts
see: link
In environments where several applications use the same base, it is usually convenient to define partial views, for example delegate role filtering to the database engine.
(*) application that only interacts with "student" users
CREATE VIEW estudiantes AS
SELECT * FROM usuarios
WHERE rol='estudiante'
ORDER BY id;
By not using aggregation or group functions the view is "updateable" and behaves like a normal table so:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Estudiante extends Model {
protected $table = 'estudiantes';
}
Allows you then to use it wave:
<?php
use App\Estudiante;
$estudiantes = App\Estudiante::all();
foreach ($estudiantes as $estudiante) :
echo $estudiante->nombre;
endforeach;
If you do not use a view you should explicitly use the filter by role, something like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Usuario extends Model {
protected $table = 'usuarios';
}
And it drifts in:
<?php
use App\Usuario;
$estudiantes = App\Usuario::where('rol', 'estudiante');
foreach ($estudiantes as $estudiante) :
echo $estudiante->nombre;
endforeach;
On the side of the application you avoid having to validate the role (which after all is only for students and non-administrators, for example), and on the side of the database engine you give more work in what you know do well and allows you to put extra constraints, for example WHERE rol='estudiante' AND tienetodopago='SI'
with which the application already receives filtered data.
Note: I built it from memory so there may be some pifie, but basically if you can use views as tables in the models (see the restrictions to insert and modify)