Fatih
Fatih

Reputation: 19

Laravel Many to Many relatioships m search from database

I have search problem in many to many relation models. Let me explain : I have online education site. And this include reservations,teachers,students. students and teachers are User's role. I want to search past reservations from database via using name or email in search input and render to admin page. Lets code

admin/searchpastreservation.blade.php
    <div class="form-group col-md-6">                                
      <input class="form-control pb-2" id="search" name="search" type="search" 
        placeholder="@lang('admin.search')">
     </div>
     <div class="form-group col-md-3">
         <button type="submit" class="btn btn-primary mb-2 form-control">Search</button>
      </div>

pastReservationController.php
public function searchpastreservation(Request $request)
 {
    $search = $request->input('search');
    $now = Carbon::now(0);
    $reservations = Reservation::where('start','<',$now)->get();
    //Reservations table columns i need reservation_start and reservation_lenght
    $students=User::whereRoleIs('student')->get();
    $teacher = User:whereRoleIs('teacher')->get()
//and i really dont know how can i write query here.if there was only one tale, it is very simple. But there where lots of table. users,role(for teacher and student),role_user(pivot table) and for reservation reservations,reservations_user(pivot table) 
}

so thats it. I am not master i am only avaricious person. i hope i could explain my problem and i hope anyone will help me.

Upvotes: 0

Views: 42

Answers (1)

OMR
OMR

Reputation: 12188

i think you should use a chain of join to get where you need,

$result= Reservation::join('reservations_user','reservations.id','reservations_user.reservation_id')
->join('users','users.id','reservations_user.user_id')
->leftJoin('role_user','role_user.user_id','users.id')
->leftJoin('roles','role_user.role_id','roles.id')
->whereDate('reservations.start','<',Carbon::now())
->where(function($query)use($search)
{
$query->where('users.email',$search)
->orWhere('users.name','like', '%' .$search . '%');
})
->select('reservations.*','users.name','users.email','roles.name', ....)->get();

Upvotes: 1

Related Questions