Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access db views using Laravel models?

I am porting a Postgres-backed web app to Laravel 4.2, and I can't see a way to utilize the existing eight or so summation views which are built in the psql db. These views preform various aggregation and averaging functions, and as such are properly part of the schema as they illustrate the relationships between the table entities.

Surely someone has had to use db views with the active record style interface of Laravel? How do you go about it?

like image 990
RSAdmin Avatar asked Oct 27 '14 17:10

RSAdmin


People also ask

How do I load a view in Laravel?

Loading a view in the controller is easy. You just need to add `view('viewname')` method while returning from the controller method. `view()` is a global helper in Laravel. In this method, you just need to pass the name of the view.

How check DB connected or not in Laravel?

Echo the Laravel database name in Blade/PHP The simplest way it to place the following script in a Blade or PHP file. This will output the name of the database or return 'none' if there is no connection. If you view it in the browser, it gives you the name of the connected database.

How do I return a view in Laravel controller?

Views may also be returned using the View facade: use Illuminate\Support\Facades\View; return View::make('greeting', ['name' => 'James']); As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory.


1 Answers

Your question is about database views and if I'm not wrong then you are talking about the dynamic table that gets created on the fly, for example, in MySql, it's possible to create a View using something like this:

CREATE VIEW students AS SELECT * FROM profiles where type='student' ORDER BY id;

So, it'll allow to query the dynamic table which is the students view here, for example:

select * from students;

This will return the filtered data from students view. So, if I'm right about your question then I think you are able to use Eloquent just like you use for real tables, for example, to create an Eloquent model for students view you can simply create it using something like this:

class ViewStudent extends Eloquent {

    protected $table = 'students';
}

So, now you can use this model as usully you may use for other tables, for example;

$students = ViewStudent::all();

It's just the same way. Since you asked for psql so I'm not sure about the syntax of that or how it works in that system but I believe it's possible same way.

like image 51
The Alpha Avatar answered Oct 14 '22 11:10

The Alpha