Search code examples
laravellimit

limiting user to only select items on laravel listbox


I would like to ask for help, please advise how to solve such problems in laravel

how to make an application like a vehicle ticket application, to limit if there are 5 people on car A, then user can not choose car A in listbox (item listbox carA disable) when booking.

I am confused where to start

I am currently thinking of creating 3 tables

users (id, name,car_id, created_at, updated_at) 
cars (id, car_name, created_at, update_at) 

I am confused what should be done to the controller Thank you very much

thanks to all of you, i can start the first step. currently

on the controller

public function create(){
    $list=MCars::all();

    return view('booking/create')->with('sent_list',$list);

}

on the view

<select name="car" value="{{ old('car')}}">
@foreach($sent_list as $a)
  <option value="{{$a->id}}">{{$a->car_name}}</option>
@endforeach
</select>

I want only cars that contain users <5 that appear on the view

maybe i should put this somewhere

SELECT DISTINCT cars.id, cars.car_name, COUNT(users.car_id) from cars INNER JOIN users ON cars.id = users.car_id


Solution

  • The relationship can be like this:

    a user belogsTo a car and the car hasMany users

    So the Car model class should be:

    ..
    class Car extends Model
    {
        public function users()
        {
            return $this->hasMany('App\User');
        }
    }
    

    And the User model:

    class User extends Model
    {
        public function car()
        {
            return $this->belongsTo('App\Car');
        }
    }
    

    Eloquent will automatically determine the proper foreign key. So, here Eloquent will assume the foreign key on the User model is car_id. Access the collection of users by accessing the users property.

    $users = App\Car::find(1)->users;
    foreach ($users as $user) {
        //
    }
    

    In the UserController use:

    $user = App\User::find(1);
    echo $user->car->name;
    

    This is how the Eloquent works!

    Now use the custom logic for limit(5).

    To retrieve the number of cars as users:

    public function getTotalUsersAttribute()
    {
        return $this->hasMany('Car')->whereUserId($this->user_id)->count();    
    }
    

    And:

    if(getTotalUsersAttribute() >= 5) {
        // dismiss this function with an err msg
    }
    // otherwise add user to car
    

    Find similar cases and solution from the official docs.