omkara
omkara

Reputation: 982

How to use count number of rows and print value in view file laravel 5.4?

app/http/controller/FirstController.php

public function delhi_property()
{
    $sql = DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->get();
    return view('index',['results'=>$sql]);
}

resources/views/index.blade.php

<h3>({{ $results->count() }}) Properties</h3>

routes/web.php

Route::get('/','FirstController@delhi_property');

I am new in laravel 5.4 Here, what am I doing I simply run a query as I mention above in my Controller and want to print numbers of rows in my view file but when I check it shows an error i.e.

Undefined variable: result (View: D:\xampp\htdocs\real_estate\resources\views\index.blade.php)

So how can I solve this problem? Please help me.

Upvotes: 1

Views: 5288

Answers (6)

Wayne Mwandi
Wayne Mwandi

Reputation: 1

In case you are using this to calculate and display the total count on a Bootstrap badge, try the following directly in the sidebar view:

<span class="badge badge-info right">{{ DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->count() }}</span>

Upvotes: 0

Ronak Chauhan
Ronak Chauhan

Reputation: 706

You can use larave's default function to count rows like example given below.

public function delhi_property()
{
    $result = DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->get();
    $total_result = count($result);
    return view('index',compact(['result','total_result']));
}

In view you can print number of rows in variable $result.

Upvotes: -1

oreopot
oreopot

Reputation: 3450

I am modifying your query a bit, will achieve the same result efficiently
    public function delhi_property()
    {
        $cityResults = DB::table('property')->whereIn('city', ['Delhi','New Delhi'])->get();
        return view('index',compact('cityResults'));
    }

In your view you can access the count as following:

<h3>{{ $cityResults->count() }} Properties</h3>

Upvotes: 0

Natvarsinh Parmar - bapu
Natvarsinh Parmar - bapu

Reputation: 1138

In controller:

public function delhi_property()
{
    $data = DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->get();
    return view('index', compact('data'));
}

In blade file:

<h3>( {{ $data->count() }} ) Properties</h3>

OR

<h3>( {{  count($data) }} ) Properties</h3>

Upvotes: 1

Eduardo Hernandez
Eduardo Hernandez

Reputation: 533

To count all rows in a query is a function for example:

count($results);

Upvotes: 0

Ravindu_Dilshan
Ravindu_Dilshan

Reputation: 171

You are returning the query result as "results", so in the view you need to access it as "$results". In the error it says undefined variable result. There is no "s" in it. So refer to the code line that error returns and check whether variable naming is correct.

Upvotes: 3

Related Questions