Query in laravel with Relationships from blade?

1

Good I have the following tables

  • Users
  • Requests
  • Servers Which are related as follows.

    • A User has several Requests
    • A Server has several Requests

Now what I need is to obtain all the servers associated with the requests that the user has without repetitions.

It should be noted that this query should be done in the blade view since in the view I am going through the services and showing them in a table.

These servers that the user has associated with their requests, I must show them in an input but that's what's easy.

So far I have been trying with the following

@foreach($solicitudes as $solicitud)    
@php


    $serversUser = \App\Servidor::where('solicitudesDeServicio', function($query){
                                                        $query->where('user_id',$solicitud->user->id);
                                                    });
                                                @endphp
@endforeach

But it has not worked since the variable $ request- > user- > id does not recognize me and throws me the exception Undefined variable: request

Then how you could get the servers that have a user associated with your request without repetitions.

Server Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Servidor extends Model
{
    protected $table = "servers";
    protected $fillable = ['url','username','password'];

    public function solicitudesDeServicio(){
      return $this->hasMany(User::class);
    }
}

Application model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SolicitudServicio extends Model
{
  protected $table ="solicitudes";
  protected $fillable = ['url', 'servicio', 'servicio_id', 'nequipos', 'nequipos_asignados','username','password', 'ndias'];
//Metodo del operador
  public function users()
  {
    return $this->belongsToMany(User::class);
  }

  public function servicio(){
    return $this->belongsTo(Servicio::class);
  }
  public function estado(){
      return $this->belongsTo(Estado::class); //es estado de solicitud
  }

  public function tipo(){
      return $this->belongsTo(Tipo::class); //Es tipo de solicitud
  }
  public function user(){
    return $this->belongsTo(User::class);
  }

  public function ciudad(){
    return $this->belongsTo(Ciudad::class);
  }
  public function servidor(){
    return $this->belongsTo(Servidor::class);
  }
}

View controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\SolicitudServicio;
use Auth;
use App\Estado;
use Illuminate\Support\Facades\Mail;
use App\Contacto;
use App\Components\SOAPRequests;

class Solicitudes extends Controller
{



  public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('isOperador');

    }


  public function view(Request $data){

      //Se agregan los filtros de la vista
      if($data->has('estado') && $data->estado == 'act'){

          //Obtengo todos los datos del filtro pero solo del usuaio logueado
          //Voy a ver si el usuario es administrador
          foreach (Auth::user()->roles as $rol) {
            if($rol->name == 'adm'){
              $registroSolicitudes = SolicitudServicio::whereHas('estado', function($query){
                $query->where('name', 'act');
              })->paginate(6)->appends('estado',$data->estado);
            }elseif($rol->name == 'opr'){
              $registroSolicitudes = Auth::user()->solicitudedeServicios()->whereHas('estado', function($eq){
                $eq->where('name', 'act');
              })->paginate(6)->appends('estado',$data->estado);;
            }
          }

      }else if($data->has('estado') && $data->estado == 'pnt'){
          //Obtengo todos lo registro en blanco y que lo pagine
          $registroSolicitudes = SolicitudServicio::whereHas('estado', function($query){
            $query->where('name', 'pnt');
          })->paginate(6)->appends('estado',$data->estado);
      }else if($data->has('estado') && $data->estado == 'fnl'){
            //Obtengo todos lo registro en blanco y que lo pagine
            $registroSolicitudes = SolicitudServicio::whereHas('estado', function($query){
              $query->where('name', 'fnl');
            })->paginate(6)->appends('estado',$data->estado);
      }else{
          //Sin filtros
          //Se muestran tanto en blanco como completados del usuario
          if(Auth::user()->isRol('adm')){
            $registroSolicitudes = SolicitudServicio::whereHas('estado', function($query){
              $query->where('name', 'pnt');
            })->orWherehas('estado',function($eq){
                $eq->where('name', 'act');
              })->orWherehas('estado',function($eq){
                  $eq->where('name', 'fnl');
                })->paginate(6);
          }else{
            $registroSolicitudes = SolicitudServicio::whereHas('estado', function($query){
              $query->where('name', 'pnt');
              })->orWherehas('users',function($eq){
                $eq->where('user_id', Auth::user()->id);
              })->paginate(6);
          }
      }

      //$soapR = new SOAPRequests();





      return view('operador.listaSolicitudes',['solicitudes'=>$registroSolicitudes] );


  }

User model

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'roles',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','profesion_id'
    ];


    public function roles(){
      return $this->belongsToMany(Rol::class);
    }

    public function provedores(){
      return $this->hasMany(ProveedorLogin::class);
    }
    //Metodo para el operador
    public function solicitudedeServicios(){
        return $this->belongsToMany(SolicitudServicio::class);
    }
    public function solicitudes(){
      return $this->hasMany(SolicitudServicio::class);
    }

    //Funcion Para comprboar roles
    public function isRol($losroles){
      $resultado = false;
      foreach (explode("|",$losroles) as $elrol) {
        foreach ($this->roles as $rol) {
          if($rol->name == $elrol){
            $resultado = true;
          }
        }
      }

      return $resultado;
    }

    public function profesion(){
      return $this->belongsTo(ProfesionUser::class);
    }

    public function company(){
      return $this->belongsTo(Company::class);
    }

}
    
asked by FuriosoJack 02.06.2017 в 23:50
source

2 answers

2

It is NOT a good practice to make a query in the view.

The second problem you have with that method of view is that you will make many requests to the database, and that is also a bad practice, as well as a potential performance problem.

Now, the query can apparently be made very easy from the controller by means of Eager Loading of the associated models, unless you do not understand the problem well:

$registroSolicitudes = SolicitudServicio::with('servidor')
    ->whereHas('estado', function($query){
            $query->where('name', 'act');
    })
    ->distinct()
    ->get();

For more information, check the Laravel documentation: link

    
answered by 03.06.2017 в 00:56
1

How about, you have an error in your query, you are missing the use($solicitud) after function($query) that's why it gives you error Undefined variable: request :

@foreach($solicitudes as $solicitud)    
  @php
    $serversUser = \App\Servidor::where('solicitudesDeServicio', function($query) use($solicitud) {
      $query->where('user_id',$solicitud->user->id);
    });
  @endphp
@endforeach

and to get all records without repeating you can use the function distinct() of laravel query builder: Query builder Docs Laravel

Note : I recommend that you do not use the fields of camelcase tables, locally this can work for you but on some servers this can give you errors or headaches.

Greetings

    
answered by 03.06.2017 в 00:52