Have you read this post? https://tray2.se/posts/use-a-view-instead-of-a-complex-eloquent-query-in-your-laravel-application
create view in laravel not working as intended
hi, i tried implementing create view of sql in laravel but unsuccessfull
//blade php
ViewRelatorioData::all();
//model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ViewRelatorioData extends Model
{
use HasFactory;
public $table = "relatorio_index_views";
}
//migration
class CreateRelatorioView extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::statement($this->createView());
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::statement($this->dropView());
}
/**
* Reverse the migrations.
*
* @return void
*/
private function createView(): string
{
return <<<SQL
CREATE VIEW relatorio_index_views AS
SELECT
formulario.matricula,
FROM formulario
SQL;
}
/**
* Reverse the migrations.
*
* @return void
*/
private function dropView(): string
{
return <<<SQL
DROP VIEW IF EXISTS `relatorio_index_views`;
SQL;
}
}
//controller
class RelatorioController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = ViewRelatorioData::select("SELECT
formulario.matricula,
FROM formulario")
->get()
->toArray();
dd($users);
}
}
what am i doing wrong here?
@peterpan26 In the blade view you do just as you would when using a table, no difference at all.
I don't think you read it properly either.
When creating a database view you create a virual table so to speak.
After that you create a model for that view and query the database just like you would a table.
Here are some examples
Model: https://github.com/Tray2/mediabase/blob/main/app/Models/BookGenreView.php
Controller: https://github.com/Tray2/mediabase/blob/main/app/Http/Controllers/Books/BooksCreateController.php
View: https://github.com/Tray2/mediabase/blob/main/resources/views/books/create.blade.php
Please or to participate in this conversation.