How to display Data in datatables in the Laravel with related tables

Asked

Viewed 263 times

0

.

In the image we have the student table that is related to discipline and discipline with teachers. I want to know how to display the data of these tables in a datatables in the language

1 answer

0

The easiest way is to create a view in your database. Create an Migration to create the view:

php artisan make:migration create_view_alunos_professores_disciplinas -m

The flag -m also creates the model to be used with the view.

Your Migration will look like this:

public function up()
{
    DB::statement("
        CREATE OR REPLACE VIEW alunos_professores_disciplinas AS
            SELECT disciplinas.nome as nome_disciplina, professores.nome as nome_professor,
            alunos.nome as nome_aluno, alunos.idade as idade_aluno, alunos.id as id_aluno,
            professores.id as id_aluno, disciplinas.id as id_disciplina
        FROM disciplinas 
            INNER JOIN professores ON professores.disciplina_id = disciplinas.id
            INNER JOIN alunos ON alunos.professor_id = professores.id;
    ");
}

public function down()
{
    DB::statement("DROP VIEW view_alunos_professores_disciplinas;");
}

(Don’t forget to give use DB; in your Migration)

Now, just use the model in this view to get the data needed for your datatable and send this data to the view via the controller.

I hope it helps.

  • I suggest you check your modeling and adjust the names of some columns, such as professores_idtable1, for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.