Home > front end >  Laravel Eloquent with condition
Laravel Eloquent with condition

Time:07-06

Can anyone help me ?

I have eloquent like this

$data = DocumentFile::with(['document_folder', 'document_request.user.profile'])
        ->where('isactive', true)
        ->when($request->search, function($query, $search) {
                $query->where('name', 'ilike', '%'.$search.'%');
        })
        ->orderBy('updated_at', 'DESC')
        ->paginate($paginate)

But it doesn't show the data what I want.


I have 3 models like this:

  • DocumentFolder, Fields: id, name
  • DocumentFile, Fields: id, name, is_private, is_active, created_by, updated_at, document_folder_id
  • DocumentRequest, Fields: id, user_id, document_file_id

1 DocumentFolder has many DocumentFile, and 1 DocumentFile has many DocumentRequest


I wanna show data with conditions:

  1. If DocumentFile is _active = true, show it, if is _active = false don't
  2. If DocumentFile is_private = false show it
  3. If DocumentFile is_private = true, must be check to DocumentRequest the user id from auth login has on DocumentRequest, if yes show it, if no don't
  4. If user login has user_id on created_by from DocumentFile, if yes show it
  5. Data can be searched by DocumentFile name
  6. Data ordered by updated_at => DESC from DocumentFile
  7. Paginate DocumentFile

CodePudding user response:

check logical grouping for query

$data = DocumentFile::with(['document_folder', 'document_request.user.profile'])
  ->where(function($query){
    $query->where('id_active', true) // 1
      ->orWhere('id_private', false) // 2
      ->orWhere('created_by', auth()->user()->id); // 3 and 4
  })
  ->when($request->search, function($query, $search) {
      $query->where('name', 'ilike', '%'.$search.'%');
    })
    ->orderByDesc('updated_at')
    ->paginate($paginate);

CodePudding user response:

Firstly you have to define all relationships ('document_folder', 'document_request.user.profile') in your models to use "with() query loading relationships" and after that try this:

$data = DocumentFile::with(['document_folder', 'document_request.user.profile'])
    ->where('is_active', true)
    ->where('name', 'like', '%'.$request->search.'%')
    ->orderBy('updated_at', 'DESC')
    ->paginate($paginate);
  • Related