Hello I am using laravel Yajra datatables, the matter is that I have a 2 variables created in a function with the name of the id.
This is all the code
<?php
namespace App\Http\Controllers\Datatables;
use App\User;
use Carbon\Carbon;
use Yajra\DataTables\DataTables;
use App\Reportes;
class ReportesDatatable
{
public function ReportesDatatable()
{
$reportes = Reportes::get();
return Datatables::of($reportes)
->editColumn('reportante', function ($reportes) {
$reportante = User::find($reportes->reportante);
return $reportante->name;
})
->editColumn('user_id_afectado', function ($reportes) {
$nameafectado = User::find($reportes->user_id_afectado);
return $nameafectado->name;
})
->editColumn('created_at', function ($reportes) {
return '<span data-popup="tooltip" data-placement="left" title="' . $reportes->timestamp . '">' . $reportes->timestamp . '</span>';
})
->addColumn('action', function ($reportes) {
return '<div class="btn-group btn-group-justified"> <a href="' . route('admin.get.editUser', $reportes->reportante) . '" class="btn btn-sm btn-secondary mr-2"> Ver Reportante</a> <a href="' . route('admin.get.editUser', $reportes->user_id_afectado) . '" class="btn btn-sm btn-primary mr-2">Afectado</a> <a href="' . route('admin.impersonate', $reportes->user_id_afectado) . '" data-popup="tooltip" data-placement="left" title="Logear como Afectado ' . $reportes->user_id_afectado . '" class="btn btn-sm btn-warning"> <i class="icon-circle-right2 text-white"></i></a></div>';
})
->rawColumns(['role', 'action', 'created_at'])
->make(true);
}
}
The variables that I need to rescue are these. I do this to no longer query the database again. I think what would be the most optimal?
1.- $reportante = User::find($reportes->reportante);
2.- $nameafectado = User::find($reportes->user_id_afectado);
I need to rescue those 2 variables and put them in the function
->addColumn('action', function ($reportes) {
return '<div class="btn-group btn-group-justified"> <a href="' . route('admin.get.editUser', $reportante) . '" class="btn btn-sm btn-secondary mr-2"> Ver Reportante</a> <a href="' . route('admin.get.editUser', $nameafectado) . '" class="btn btn-sm btn-primary mr-2">Afectado</a> <a href="' . route('admin.impersonate', $reportes->user_id_afectado) . '" data-popup="tooltip" data-placement="left" title="Logear como Afectado ' . $nameafectado . '" class="btn btn-sm btn-warning"> <i class="icon-circle-right2 text-white"></i></a></div>';
})
The variable would remain in this way with the rescued variables.
Currently if I put the variables they tell me that they do not exist because they are in a different function I think.
How to make those variables global?
Reportesmodel setup with a relation to theUsermodel. If you have a relation, then you can use eager loading. If you can add yourReportesmodel into your question, it may help understand how the relation is.