Daniel Alsaker
Daniel Alsaker

Reputation: 193

How to check for specific value in database and act upon it. Laravel 4.2

I'm kinda new to Laravel, and I'm wondering how I can check for a specific value in the databse? I have 5 different category id's in my databse, and I wanna do a check on the databse and act differently depending on what the category id is.

I'm thinking something like this:

if ($example = Example::where('category_id', '=', '1')->first()) {
    echo "The category id is 1";
}

or maybe:

$example = Example::where('category_id', '=', Input::get('category_id'))->first();
if ($example === 1) {
    echo "The category id is 1";
}

I also tried other things, based on what I already have working, but cannot seam to get this feature to work.

Upvotes: 1

Views: 106

Answers (1)

Saumya Rastogi
Saumya Rastogi

Reputation: 13703

You can use firstOrFail() method of Laravel like this:

$example = Example::where('category_id', '=', '1')->firstOrFail();
if ($example) {
    echo "The category id is {$example->id}";
}
return "error";

The firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown

UPDATE:

For fetching and checking each rows, use all() method and iterate through each rows to get your desired results.

$examples = Example::all();
foreach($examples as $example) {
    if ($example->category_id == 1) {
        echo "echo here the 1 thing....";
    } elseif($example->category_id == 2) {
        echo "echo here the 2 thing....";
    } else {
        echo "something else"
    }
}

Hope this helps!

Upvotes: 1

Related Questions