Ranjeet Karki
Ranjeet Karki

Reputation: 2647

How to use Laravel query builder

How can I use laravel query builder for following query($sql)? I mean I want to use like this

$sql=\DB::table('animal).....but I am unable to do so. Please help me

foreach ($animalsTypes as $animal)
          {
    //some code here...
             $sql ="SELECT count(*) FROM animals WHERE animal='$animal'";
              $records = \DB::select($sql);

               foreach($records as $record){
         //some code here...      
         }
    }

This query in not working, it doesnot display any results and their count

  $records = \DB::table('animals')
                 ->select(DB::raw('count(*)'))
                 ->where('animal', '=', '$animal')
                 ->get();

Upvotes: 2

Views: 291

Answers (3)

Loko
Loko

Reputation: 6679

If you want to count:

$amount_of_animal = DB::table('animals')->where('animal',$animal)->count();

If you want the results as well:

$animal = DB::table('animals')->where('animal',$animal)->get();

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31749

Try with -

DB::table('animals )->where('animal', $animal)->count();

Upvotes: 0

Noman
Noman

Reputation: 4116

read out the documentation it has complete guide for select and other statements. Laravel documentation

$users = DB::table('users')->get();

foreach ($users as $user)
{
    var_dump($user->name);
}

Upvotes: 2

Related Questions