getting Locale session on Laravel and selecting query accordingly - laravel

I am trying to just select a sql query depending on the session set for the locale language. Yet, as simple as it should be, now I am getting at the View an "invalid argument for the foreach array", that is, it is not passing arguments. Before having the check locale addition, it did return correctly for English, but as I am adding now another language, the IF is not taking decisions because the check session somehow is not properly written or I dont know what. I have been googling and it read like this:
if (\Session::get('locale') == 'en')
{
$listings = \DB::table('properties')
->join('english_descriptions', 'property_id', '=', 'properties.id' )
->select('endescription','properties.id','houses1','price', 'bedrooms', 'm2', 'entitle')
->get();
return $listings;
}
else{
if (\Session::get('locale') == 'es')
{
$listings = \DB::table('properties')
->join('spanish_descriptions', 'property_id', '=', 'properties.id' )
->select('esdescription','properties.id','houses1','price', 'bedrooms', 'm2', 'estitle')
->get();
return $listings;
}
My controller function looks like this now:
public function showListings()
{
var_dump(\Session::getLocale());
$listings = Property::returnListings();
return \View::make('listings', compact('listings'));
}

Make sure you always have a fallback return value when using if-statements.
$listings = []; // this will be the default return value if no condition is met
if (\Session::get('locale') == 'en') {
// query for listings in 'en'
}
else if (\Session::get('locale') == 'es') {
// query for listings in 'es'
}
return $listings;
Now for the locale Session, dump the value of \Session::get('locale') to check if the value is really en or es.
You might want to retrieve your locale value not from session but from the App itself using \App::getLocale();

Related

How to remove item from laravel query result and get it?

In Laravel project I am making a database query
$addresses = DB::table('residences')->where('user_id', '=', Auth::user()->id)->get();
I want to get one address from that query result, if it exists, where 'id' field equals to 10 for example. But I want to remove that address from $addresses query result simultaneously. Is there a simple way to do that?
You can use the reject() method on the $addresses collection, i.e:
$my_result = false;
$addresses = $addresses->reject(function ($value, $key) use (&$my_result) {
if($value->id == 10){
$my_result = $value;
return true
}
return false;
});

whereBetween doesnt exist and i cant apply paginate

I've this method:
public function indexGuest($idAzienda, Request $request){
$companyId = $idAzienda;
$ddts = Ddt::where('company_id',$companyId);
$ddt_urls= Ddt_file_url::all();
if($request->start_date || $request->end_date){
$ddts->whereBetween('created_at',[new Carbon($request->start_date),new Carbon($request->end_date)]);
}
$ddts->paginate(10);
return view('guest.ddt-management')->with('ddts', $ddts)->with('ddt_urls',$ddt_urls)
->with('companyId',$companyId);
}
My start_date and end_date comes in strings like "yyyy-mm-dd".
I've tried to pass it straight to the query and like in the example like a carbon object with no hope!
After executing the query (now only the one without the wherebeeteween clause) i cant apply the method "paginate" to the collection, no error are raised but when i pass it to the view, the "link()" method not work and raise an error again.
where I wrong?
Laravel 5.4
Structure your wheres like this.
public function indexGuest($idAzienda, Request $request) {
[...]
$ddts = Ddt::where('company_id', $companyId)
->where(function($query) use ($request) {
if($s = $request->get("start_date") {
$s_date = Carbon::parse($s)->format("Y-m-d");
$query->whereDate("created_at", ">=", $s_date);
}
if($e = $request->get("end_date") {
$e_date = Carbon::parse($e)->format("Y-m-d");
$query->whereDate("created_at", "<=", $e_date);
}
})
->paginate(10);
[...]
}

Pagination not working on multiple querying

I have a multiple query, but for some reason the pagination is not working, i dont no if the ussue is the way i construct it.
My code:
$query = \DB::table('products');
if ($request->has('type') && $type) {
$query->where('product_type_id', $type);
}
if ($request->has('material') && $material) {
$query->join("product_attribute_materials","products.id","=","product_attribute_materials.product_id")
->whereIn("product_attribute_materials.product_material_id", $material);
}
if($request->has('businessarea') && $area){
$query->join("product_attribute_businessareas","products.id","=","product_attribute_businessareas.product_id")
->whereIn("product_attribute_businessareas.product_businessarea_id", $area);
}
$products = $query->paginate(15);
You need to append the query string to the pagination using append() on $products
Passing array with the keys that you want to pass the query string, will return its value on the next request.
To confirm this, chick the href value from your browser before clicking on page number 2.
$products = $query->paginate(15)->appends(['type', 'material', 'businessarea']);

Retrieving correct data from the database using Laravel Eloquent

I am trying to retrieve data from the database however I am not getting right results. It looks like my "If" statements are not working properly as I am getting some data from the "$sale->whereRaw" query which is at the beginning of foreach. What I am doing wrong?
I am working with Laravel 4.2.
Controller:
$matches = Match::where('PeopleID', '=', $id);
$sales = Sale::leftJoin('property', 'sales.property_id', '=', 'property.property_id')
->where('Status', '=', 'ForSale');
foreach($matches as $match)
{
$county = $match->county;
$sales->whereRaw("match (`county`) against (?)", array($county));
if($match->tenureFh == '1')
{
$sales->where('Tenure','=','FH');
if($match->minPrice != '0')
{
$sales->where('PriceFreehold', '>=' , $match->minPrice);
}
if($match->maxPrice != '0')
{
$sales->where('PriceFreehold', '<=', $match->maxPrice);
}
}
if($match->tenureLh == '1')
{
$sales->where('Tenure', '=', 'LH');
if($match->minPrice != '0')
{
$sales->where('PriceLeasehold', '>=' , $match->minPrice);
}
if($match->maxPrice != '0')
{
$sales->where('PriceLeasehold', '<=', $match->maxPrice);
}
}
}
$results = $sales->orderBy('sales.updated_at', 'asc')->get();
Match Model
public function people()
{
return $this->belongsTo('People', 'PeopleID', 'PeopleID');
}
public function sale()
{
return $this->hasMany('Sale');
}
Sale Model
public function match()
{
return $this->belongsTo('Match');
}
People Model
public function matches()
{
return $this->hasMany('Match', 'PeopleID', 'PeopleID');
}
public function sale()
{
return $this->hasMany('Sale');
}
#uptade
Currently I am getting the results from this statement:
$sales->whereRaw("match (`county`) against (?)", array($county));
Which is good however I need to filter the results further and this is where the "if" statements come in to place.
"Match" contains different searching credentials for each customer. If the candidate is looking for product with "Tenure: FH" In county "A" I need to display products with county "A" and which "Tenure" is "FH" (That is why I have made some those "if" statements). However those statements does not seem to work as I am getting ALL results for county "A" which "Tenure" is "FH" or other than "FH".
So the problem must be with those "Ifs" as they are not filtering the result further.
Imagine you have signed in with cars dealership website and you are looking for a red, 4 door car however the result you are getting is ALL 4 door cars but with all different colours (but you wanted a red one right?) - This is how it works at the moment.
I think you can do dd(DB::getQueryLog()); to see what query you get in the end.

Laravel - Trying to get property of non-object in chained view

Having a small problem with retrieving a new object on my view. I keep getting the error 'Trying to get property of non-object'.
The field I am trying to display 'oil_gas_skillsgap' is a valid field and when I do a simple return it spits out...
[{"oil_gas_job_id":"4","industry_job_id":"43","oil_gas_skillsgap":"test text here"}]
CONTROLLER
public function showjob($slug)
{
$job = OilGasJob::where("slug", "=", $slug)->first();
if (is_null($job))
{
return Redirect::to('/');
} else {
$jobId = $job->id;
$roleId = Session::get('industryrole');
$skills = DB::table('industry_job_oil_gas_job')
->where('oil_gas_job_id', '=', $jobId)
->where('industry_job_id', '=', $roleId)
->get();
return View::make('job')
->with('job', $job)
->with('skills', $skills);
}
}
VIEW
{{ $job->job_title}}
{{ $skills->oil_gas_skillsgap }}
$skills is probably an array, not an object, even if the query has only one result.
If you know for a fact that your query will return one result, use first() and you'll get it as an object directly.
$skills = DB::table('industry_job_oil_gas_job')
->where('oil_gas_job_id', '=', $jobId)
->where('industry_job_id', '=', $roleId)
->first();
Otherwise, remember the following: when using the DB class for queries, Laravel will always return an array. If you use an Eloquent model, it will return an Illuminate\Support\Collection object. In both cases that is true even if no row is found (the array or Collection will be empty). The first() method, on the other hand, will either return an object (stdClass when using DB, or a model when using Eloquent) or null.
#user3189734,
job_title is not a part of $job collection, that is why it is throwing 'Trying to get property of non-object'.

Resources