Wednesday, March 8, 2017

Laravel 5 showing 2 relationships as 1 after search input.

I'm building a administration application for a car garage. In this application I want a page where the admin can search through all cars. When he presses a button, all the cars with that search que will be echod on the screen. Atm a admin can search on a brandname(OPEL, SUZUKI, SUZUKI etc) and an admin can search on the year a car has been build(1987, 2001, 2003 etc). If there's a car with those criteria, it will be shown as follows:

BRANDNAME
Licentsplate: LICENSEPLATE
Build: BUILDYEAR

In this image below you can see it on my live page: Search on brand Search on year
Question: A car belongs to a user and I want to show the user that is the owner of the car aswel, but that's an other relationship. How can I show that user aswel?

MODELS
User

class User extends Authenticatable
{
    use Notifiable;
    // Make relation between users and a car.
    // One user can have multiple cars.
    public function cars()
    {
       // Car::class == App\Car
       return $this->hasMany(Car::class);
    }
 }

This table has the following records: ID, name, lastname, email, password.
Car

class Car extends Model
{
   // Make relation between cars and a user.
   // One user can have multiple cars.
   // One car belongs to a user.
   public function user(){
      return $this->belongsTo(User::class);
   }
   public function brand(){
      return $this->belongsTo(Brand::class);
   }
   protected $fillable = [
      'user_id', 'brand_id', 'year', 'licensplate'
   ];
}

The cars table has the following records: id, user_id, brand_id, year, licenseplate.
The relationship:
('user_id')->references('id')->on('users')
('brand_id')->references('id')->on('brands')
Brand

class Brand extends Model
{
   protected $fillable = [
      'brandname'
   ];
   public function cars(){
     return $this->hasMany(Car::class);
  }

}

The brands table has the following fields: id, brandname Controller This is de code that i have atm for the search button:

public function show(){
    $input = request('searchfield');
    if(empty($input))
    {
        return back();
    }

    else if(is_numeric($input))
    {
      // Search on year
            $brands = Brand::with(['cars' => function ($q) use ($input){
                $q->where('year', $input);
            }])->get();
        return view('content.cars.index', compact('brands'));
    }
    else
    {
        // Search on brandname
        $brands = Brand::with('cars')->get()->where('brandname', $input);
        return view('content.cars.index', compact('brands'));
    }
}



via Koen van de Sande

Advertisement