Search code examples
laravel-5.3

Laravel - getting data of the user from database by specific criterion


I have a users table which stores the names of my users and applications table which stores all applications made by the user...the user makes application for transport and the application is printed on the admins page so that the admin may know which user made the application.

How do I retrieve the name of the user who applied? How do I get all users that applied for a van?

One user has many admins as follows:

user model:

public function admin(){
  return $this->hasMany('Martin\Models\admin');
}

admin model:

public function application()
{
    return hasMany('Martin\Models\Application');
}

application table schema:

Schema::create('applications', function (Blueprint $table)
{
    $table->increments('id');
    $table->string('user_id')->nullable();
    $table->string('destination');
    $table->date('departure_date');
    $table->integer('Number_of_days_hired');
    $table->timestamp('departure_time')->nullable();
    $table->boolean('approved')->default(0);
    $table->timestamps();
});

Solution

  • $applications = Application::all();  //get all applications. Application is your Eloquent model of the Applications table
    
    $userIds = $applications->pluck('user_id'); // get ids from all the users that applied
    
    $names = User::whereIn($userIds)->pluck('name'); // name is equal to the name of the column in database which stores name of the User (you didn't specify that in your question)
    
    foreach($names as $name) {
        // do something with name
    }
    

    UPDATE

    there are 2 ways to find the users who applied for specific thing:

    1. blade file:

    @foreach($users as $user)
        @if($user->applied_for_van) // put your criteria for van application here
            <td>{{$user->name}}</td>
        @endif
    @endforeach
    

    2.1 file where you fetch all users:

    $users_who_applied_for_van = [];
    
    foreach($users as $user) {
        if($user->applied_for_van) {
            $users_who_applied_for_van[] = $user; // this equal to array_push. add user to the array basically
        }
    }
    

    2.2 blade file:

        @foreach($users_who_applied_for_van as $user)
            <td>{{$user->name}}</td>
        @endforeach