mercredi 3 octobre 2018

Laravel - Search Filter in Relationship Problem in Fetching Data

Trying to get data from a table "mobiles", and its related entry in Stock. While my search keyword is mobile model, see Mobiles table below

enter image description here

and related table "Stock" is below also

enter image description here

Mobile Model is:

class Mobile extends Model
{
    public function company(){
        return $this->hasMany(Company::class);
    }
    public function stocks(){
        return $this->hasMany(Stock::class);
    }
}

Stock Model is:

class Stock extends Model
{
    public function company(){
        return $this->belongsTo(Company::class, 'company_id');
    }
    public function mobiles(){
        return $this->belongsTo(Mobile::class, 'model_id');
    }
}

index method of Stock is:

public function index(Request $request)
    {
      $request->session()->put('search', $request
        ->has('search') ? $request->get('search') : ($request->session()
          ->has('search') ? $request->session()->get('search') : ''));

      $request->session()->put('field', $request
        ->has('field') ? $request->get('field') : ($request->session()
          ->has('field') ? $request->session()->get('field') : 'model_id'));

      $request->session()->put('sort', $request
        ->has('sort') ? $request->get('sort') : ($request->session()
          ->has('sort') ? $request->session()->get('sort') : 'asc'));

      $stocks = new Stock();

      $stocks = $stocks->where('model_id', 'like', '%' . $request->session()->get('search') . '%')
      ->orderBy($request->session()->get('field'), $request->session()->get('sort'))
      ->paginate(5);

      if ($request->ajax()) {
        return view('pages.stock.index_stock', compact('stocks'));
      } else {
        return view('pages.stock.ajax', compact('stocks'));
      }      
    }

Problem is that i can search using model id because search filter is set on "stock" table, column "model_id". how can i search by writing mobile model name that is existing in table "mobiles", after searching model it should display complete info related to searched mobile model.

Thanks in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire