Laravel 5.5 - findorFail and check for another value - laravel

I am using try in Laravel 5.5 like this...
try {
$fruit = Fruit::findOrFail($id);
}
But I would like to check that not only that it finds the Fruit with the supplied ID but that it also has a fruit_color of 'red'
Do I need to do this with a 'with' statement?
I know I can run another check afterwards but wondered if I could do this all in one statement?

A few things. First, throwing an exception here is the wrong way to handle the ‘if’ situation. If you plan on a situation where a value isn’t return, then this isn’t the proper use of an exception. To answer your question:
$fruit = Fruit::where(‘id’, $id)->where(‘color’, ‘red’)->get();
This returns a collection of items meeting your criteria. Next to test if the collection is empty (no fruit) you can do the following:
if($fruit->isEmpty()) {
//handle empty collection
}
Hope this helps! The Laravel documents for collections kicks a**. I’d recommend reading further there.

You just need to add your extra conditions in before you call the find:
try {
$fruit = Fruit::where('fruit_color', 'red')->findOrFail($id);
}

Try this code
$fruit = Fruit::where(‘id’, $id)->where(‘color’, ‘red’)->first();

Related

Method Illuminate\Database\Eloquent\Collection::orderby does not exist

$posts = Post::all()->orderby('created_at','desc')->where('usr_id','=',session('LoggedUser'))->get();
return view('admin.profile',compact('userInfo' , 'posts'));
i am making a custom auth for a journal activity but i cant sort the content i shows this error
"Method Illuminate\Database\Eloquent\Collection::orderby does not exist. "
$posts = Post::where('usr_id','=',session('LoggedUser'))->orderby('created_at','desc')->get();
True query like that. When you take all() already query done.
Change it to:
$posts = Post::where('usr_id','=',session('LoggedUser'))->orderby('created_at','desc')->get();
you cant use all() and orderBy because all() does not allow the modification of the query.
I believe this might be because you typed orderby instead of orderBy (notice the uppercase). See laravel orderBy documentation if needed.
Plus, as mentionned by other, don't use all() if you need to do other thing (where clause, order by, etc) in you query.
Change the orderby to orderBy. This could be the reason you are getting the error.
$posts = Post::all()->orderBy('created_at', 'DESC')->where('usr_id','=',session('LoggedUser'))->get();
return view('admin.profile',compact('userInfo' , 'posts'));
Or...
If you want to get specific number of posts you can do it this way to avoid using the Post::all
$posts = Post::orderBy('created_at', 'DESC')->where('usr_id','=',session('LoggedUser'))->paginate(5);
return view('admin.profile',compact('userInfo' , 'posts'));
Yeah this is pretty confusing and just got me as well.
The actual problem isn't the capitilization typo (orderby versus orderBy) but rather the fact that you're using ->all() instead of just Model::orderBy()->...
The moment you use ->all() the object is transformed to another type of collection object and the normal methods one would expect do not exist.
In this case you should rather use sortBy().
See here.

How to check laravel collection is empty in blade file?

I have added the condition like this #if(!empty($param)) but not working.
assuming $param is a collection here, you can use isEmpty() or isNotEmpty() method like this:
#if($param->isNotEmpty())
Or
#unless($param->isEmpty())
You can use isempty method of laravel collection to check whether a collection is empty or not. For more detail you can check it in their document.
Laravel Collection: isempty Method
You can use the count() method and do something like this :
#if($collection->count())
More details here.
This also works:
#if(count($param) > 0)

Laravel update query use

I used this query to update the status column.
$val="1";
vehicles::where('id' , '=' , $veh_status)->update(['status' => $val]);
But when I submitted the status value doesn't change.
you can trace your query by using ->toSql() method !
try this to find whats happening in back
Not sure what the problem is there because you haven't given much info to work with, but you can check these suggestions:
Check if the column is set to be mass assignable in the model class, that is, it is in the fillable[] array.
make sure the id you pass to the where() function is valid.
Try using another function, save() which will achieve the same results you seek, like this;
// filter the vehicle
$vehicle = vehicles::where('id', '=', $veh_id)->first();
or
$vehicle = vehicles::find($veh_id);
$vehicle->status = 1;
$vehicle->save();
Lastly, I noticed your id variable you pass to the where the () function is called $veh_status "presumably - vehicle status" and not $veh_id, "presumably - vehicle id" so probably check that out.
Ref: Laravel Model Update documentation

Eloquent Collection: Counting and Detect Empty

This may be a trivial question but I am wondering if Laravel recommends a certain way to check whether an Eloquent collection returned from $result = Model::where(...)->get() is empty, as well as counting the number of elements.
We are currently using !$result to detect empty result, is that sufficient? As for count($result), does it actually cover all cases, including empty result?
When using ->get() you cannot simply use any of the below:
if (empty($result)) { }
if (!$result) { }
if ($result) { }
Because if you dd($result); you'll notice an instance of Illuminate\Support\Collection is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... } which will always return true.
To determine if there are any results you can do any of the following:
if ($result->first()) { }
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }
You could also use ->first() instead of ->get() on the query builder which will return an instance of the first found model, or null otherwise. This is useful if you need or are expecting only one result from the database.
$result = Model::where(...)->first();
if ($result) { ... }
Notes / References
->first() http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_first
isEmpty() http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty
->count() http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count
count($result) works because the Collection implements Countable and an internal count() method: http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count
Bonus Information
The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason it can be confusing to know what one you’re working on. The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like ->all() ->first() ->lists() and others). Those methods also exist on the Collection object, which can get returned from the Query Builder if there are multiple results. If you're not sure what class you're actually working with, try doing var_dump(User::all()) and experimenting to see what classes it's actually returning (with help of get_class(...)). I highly recommend you check out the source code for the Collection class, it's pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.
Laravel 5.2 Collection Class
Laravel 5.2 Query Builder
I think you are looking for:
$result->isEmpty()
This is different from empty($result), which will not be true because the result will be an empty collection. Your suggestion of count($result) is also a good solution. I cannot find any reference in the docs
I agree the above approved answer. But usually I use $results->isNotEmpty() method as given below.
if($results->isNotEmpty())
{
//do something
}
It's more verbose than if(!results->isEmpty()) because sometimes we forget to add '!' in front which may result in unwanted error.
Note that this method exists from version 5.3 onwards.
There are several methods given in Laravel for checking results count/check empty/not empty:
$result->isNotEmpty(); // True if result is not empty.
$result->isEmpty(); // True if result is empty.
$result->count(); // Return count of records in result.
I think better to used
$result->isEmpty();
The isEmpty method returns true if the collection is empty; otherwise,
false is returned.
According to Laravel Documentation states you can use this way:
$result->isEmpty();
The isEmpty method returns true if the collection is empty; otherwise, false is returned.
I think you try something like
#if(!$result->isEmpty())
// $result is not empty
#else
// $result is empty
#endif
or also use
if (!$result) { }
if ($result) { }
You can do
$result = Model::where(...)->count();
to count the results.
You can also use
if ($result->isEmpty()){}
to check whether or not the result is empty.
so Laravel actually returns a collection when just using Model::all();
you don't want a collection you want an array so you can type set it.
(array)Model::all(); then you can use array_filter to return the results
$models = (array)Model::all()
$models = array_filter($models);
if(empty($models))
{
do something
}
this will also allow you to do things like count().
You can use: $counter = count($datas);
The in_array() checks if a value exists in an array.
public function isAbsolutelyEmpty($value)
{
return in_array($value, ["", "0", null, 0, 0.0], true);
}
You want to check these two cases of count().
#1
If the result contains only a single row (one record) from the database by using ->first().
if(count($result)) {
// record is exist true...
}
#2
If result contain set of multiple row (multiple records) by using ->get() or ->all().
if($result->count()) {
//record is exist true...
}

How do I filter a collection by a YesNo type attribute?

I have a ‘featured’ attribute, which has a Yes/No select-list as the admin input. I presume that the values for Yes and No are 1 and 0, as they are for every other Yes/No list. However, if I try and filter a collection using the ‘featured’ attribute, it doesn’t work:
$feat_attribute = $_product->getResource()->getAttribute($featuredattribute)->getSource()->getOptionId(1);
But, if I make a ‘featured’ attribute with a dropdown, and write my own Yes and No, then it works as below:
$feat_attribute = $_product->getResource()->getAttribute($featuredattribute)->getSource()->getOptionId('Yes');
Anyone any ideas? I’ve also tried values as true/false, yes/no, on/off etc, but no joy.
This seems to be an old thread, but anyway I just had the same issue, I set the attribute to be visible in product listing and product view, and then apply addAttributeToFilter(feature_product_attribute, 1) for Yes/No type.
Maybe you are supposed to use '1' and '0' instead of the integer-values?
Like:
$feat_attribute = $_product->getResource()->getAttribute($featuredattribute)->getSource()->getOptionId('1');
Whenever Magento's behavior is confusing me, I start hacking on the core source (a development copy, of course) to see what it's doing and why not doing what I think it should. I haven't done much playing around with the Admin UI stuff so I don't 100% understand your question, but take a look at the getOption function
File: /app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Abstract.php
public function getOptionId($value)
{
foreach ($this->getAllOptions() as $option) {
if (strcasecmp($option['label'], $value)==0 || $option['value'] == $value) {
return $option['value'];
}
}
return null;
}
I'd add some Mage::Log and/or var_dump calls in there for the values of $option['label'] and $option['value'] and see why your comparison is failing.

Resources