What I'm trying to do is, put together a search query by joining two tables together. I have a very simple fictional Real Estate site, where a user can search for listings using multiple options, such as searching by city. The way I have it set up is I have a City model and table, which contains a list of cities and a Listing model, controller, and table.
The city table is set up with these fields id name. And for the listings table, the city_id field connects with id field in the city table. On my homepage, I have an option where a user types in a city, the results are sent to a results page with all or any listings from that city using the tables from above. This is where I'm running into problems.
This is the error I get when I run the query:
Trying to get property of non-object
Here's the code for the form on the homepage:
`index.blade.php
<form action="/search" method="GET" role="search">
{{ csrf_field() }}
<div class="form-wrapper">
<input type="text" class="search-query" name="q" placeholder="Search citys" autocomplete="off">
</div>
<button type="submit" class="btn btn-success">SEARCH</button>
</form>
Here's my controller that does the query (listingcontroller)
public function listingsresults()
{
$q = Input::get ( 'q' );
$listing = Listing::join('cities', 'listings.city_id', '=', 'cities.id')
->select('listings.city_id', 'cities.name')
->where ( 'name', 'LIKE', '%' . $q . '%' )
->paginate(8);
if (count ( $listing ) > 0)
return view ( 'front-end/listingsresults' )->withDetails ( $listing )->withQuery ( $q );
else
return view ( 'front-end/listingsresults' )->withMessage ( 'No Details found. Try to search again !' );
}
`
My Listing Model:
` class Listing extends Model
{
protected $fillable = [
'street',
'city_id',
'state_id',
'price',
'beds',
'baths',
'sqft',
'descrip',
'category_id',
'user_id',
'state_id',
'fullpic_id',
'extrapicone_id',
'extrapictwo_id',
'extrapicthree_id',
'extrapicfour_id',
'',
];
// protected $primaryKey = 'id';
public function user(){
return $this->belongsTo('App\User');
}
public function state(){
return $this->belongsTo('App\State');
}
public function city(){
return $this->belongsTo('App\City');
}
public function category(){
return $this->belongsTo('App\Category');
}
public function fullpic(){
return $this->belongsTo('App\PhotoListing');
}
}
`
My City Model:
` class City extends Model
{
protected $fillable = ['name'];
}
`
Any ideas on why I'm getting this error? I'm not sure if it is because I'm not structuring my query right or not. Also is this the best way to structure the Models, Controllers, and Views I ask because I'm still trying to get a hang of Laravel, and MVC in general.