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

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'.

Related

Laravel View error query Property does not exist on this collection instance

I have this function in my controller :
public function edit(funcionario $item){
$ferias = feria::join ('funcionarios','funcionarios.id','=', 'ferias.id_funcionario')
->where( 'ferias.id_funcionario', '=', $item->id)
->get(['ferias.id_funcionario', 'ferias.n_ferias_disponiveis', 'funcionarios.id']);
return view('painel-admin.utilizadores.edit', ['item' => $item, 'ferias' => $ferias]);
}
The "Item" work perfectly but "ferias" not.
I want to show the values ​​that are inside the vacation field.
strong text
value="{{$ferias}}" This it work and show this :
[{"id_funcionario":23,"n_ferias_disponiveis":22,"id":23}]
but i try this value="{{$ferias->n_ferias_disponiveis}}" show this error :
Property [n_ferias_disponiveis] does not exist on this collection instance
return value in collection, so you have to make a foreach loop to get the particular one field...
foreach($ferias as $feria)
{
$name = $feria->n_ferias_disponiveis;
}

Filter based on collection or sub-attribute

My user model has a 'prevregistration' attribute
public function prevregistration()
{
return $this->hasMany(Prevregistration::class, 'prevregistration_userid');
}
My prevregistraton model has a 'prev' attribute
public function prev()
{
return $this->hasOne(Prev::class,'prev_id', 'prevregistration_previd');
}
In my controller I show prevregistrations for the current user:
mynextprevs = Auth::user()->prevregistration ;
Now I want to only show prevregistrations from which the connected prev its prev_date in the future, like this:
$mynextprevs = Auth::user()->prevregistration::whereDate('prev_date', '>=', Carbon::today()->toDateString());
But then I get:
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::whereDate does not exist.
I also tried like this:
$mynextprevs = Auth::user()->prevregistration->prev::whereDate('prev_date', '>=', Carbon::today()->toDateString());
But then I get:
Property [prev] does not exist on this collection instance.
Should I/how can I filter the collection? I'm curious why Auth::user()->prevregistration->prev is not working, since that are attributes.
Thanks
You need to use the condition whereHas on your prevregistration
$mynextprevs = Auth::user()->prevregistration()->whereHas('prev',function($prev) {
$prev->whereDate('prev_date', '>=', Carbon::today()->toDateString());
})->get();
Notice we used the relation as a method prevregistration() to access it as a query builder and not as a collection hence the need for the ->get() at the end.

Laravel validation for uniques value

I have multiple customers ,and each customers can have a list of names (customers_name) that can be "aka" or "previous" and for each type value must be unique. Message: "Call to a member function pluck() on array"
$customerPrevious = [];
if($customer_name['name_type'] == 'previous'){
// previous customer_names from server
$customerPrevious = $customer->customerNames()->where('name_type', '=', 'previous')->pluck('name')->toArray();
// previous customer_names from request
$customerPreviousRequest = $request->customer_names->where('name_type', '=', 'previous')->pluck('name')->toArray();
$duplicateValue = array_diff($customerPrevious,$customerPreviousRequest);
if($duplicateValue.length){
return response($exception->getMessage(), 404);
}
}
Your error is because inside $request->customer_names you get array.
->pluck() is for collections.
So you can change:
$request->customer_names->pluck('name')
with
Arr::pluck($request->customer_names, 'name')
More about Arr::pluck() you can find here.

laravel: odd behavior when query is empty

I have a model
I call it this way:
Sight::filter(['type'=>'menu']);
and in model:
public function scopeFilter($query,$params)
{
return $query
->wherePublish(1)
->whereIn_special(1)
->latest()
->first();
}
when there is one or more records, it works normally.
but when database is empty I get an odd behavior:
with dd(Sight::filter(['type'=>'menu']))
or
$query
->wherePublish(1)
->whereIn_special(1)
->latest()
->first();
dd($query);
I got this result:
But with
dd(
$query
->wherePublish(1)
->whereIn_special(1)
->latest()
->first();
)
I got Null so it is right!
how can I return Null? what is my wrong?
You shouldn't be calling first() inside of a scope - you are only meant to adjust the query by constraining it. You should call first() in your chain after applying the filter() scope. If you want to use the same syntax rather than chaining like that you would be best to define a custom static method.
public static function filter($params)
{
return self::wherePublish(1)
->whereIn_special(1)
->latest()
->first();
]
Also note that in your example your scope accepts an argument (and you pass it one) but it isn't actually used in your code.

Laravel 4 #foreach

Using a resourceful UsersController and $users.
It seems that when $users has only 1 entry, the #foreach loop doesn't work?
In UsersController:
public function show($id) {
$users = User::find($id);
return View::make('users')->with('users',$users);
}
If I just use "return $users", the value of $users is:
{"id":"1","username":"user1"}
In users.blade.php:
#foreach($users as $user)
{{$user->username}}
#endforeach
When there are 2 or more users it worked, but with URI app.com/users/1, it only returns one (see above) and the new error is:
"Trying to get property of non-object"
Why is this an error in users.blade.php?
It's more a question of what User::find($id) is returning..
Query builder methods return an instance of the Collection class, which represents a collection of Models. For instance, here we get back a Collection containing one Model.
$users = User::where('id', '=', $id)->get();
However the find() method returns a single Model
$users = User::find($id);
A single Model isn't iterable in the same way as a Collection, which returns a Model with each iteration, hence the error you're seeing!

Resources