Makis Theotokis
Makis Theotokis

Reputation: 27

Store the result of an sql query to a variable (without For each) (Laravel)

I'm new to Laravel and i need your help please.

This runs on my controller and the result should be "3" as long as I have 3 rows with that title in the same table.

 $countcategories = DB::table('categories')
                ->select(DB::raw('count(title) as result'))
                ->where('title','=','dsds')
                ->get();

I'm passing the query result to the view like this->with('counts', $countcategories)

And now my questions are:

  1. In the view I can only display the result by using foreach. Why? My query returns only one row.
  2. I want to store the query result in a variable inside my controller in order to use that result. How can I do that?

Thank you very much!

Upvotes: 0

Views: 2336

Answers (2)

boxfrommars
boxfrommars

Reputation: 71

you should use ->first() method:

$countcategories = DB::table('categories')
            ->select(DB::raw('count(title) as result'))
            ->where('title','=','dsds')
            ->first();

Upvotes: 2

Nabil Kadimi
Nabil Kadimi

Reputation: 10394

  1. What you are getting are rows from a result, it tunrs out there is only one in your situation.
  2. You have already done that.

Anyways, here's my approach:

// The result
$categories = Category::where('title','=','dsds');
foreach( $categories->all() as $category ) {
    echo $category->title . "\n";
}

// The count
echo $categories->count();

Upvotes: 0

Related Questions