7

im trying to use mysql_num_rows in laravel but laravel says it not the same way like in 'raw php'

example:

$users = DB::table('users')
         ->where('username', '=', $username)
         ->where('password', '=', $password)
         ->get();

what i want to do:

$count = mysql_num_rows($users);

   if($count > 0 ){

      $user->login = $request->login;
      $user->email = $request->email;
      $user->password = $request->password;

      Auth::login($user);
      return redirect("/");
      }else{
         return "datos incorrectos";
      }

what laravel says:

Call to undefined function App\Http\Controllers\Auth\mysql_num_rows()

PD: its not philosophy of code just make commets about that question, i dont want answers like "u gonna crypt that thing?", "why not use [insert my faborite ORM]" is just a simple question THANKS

indian
  • 75
  • 1
  • 1
  • 5
  • If this is the same project that you were working on a few days ago, you should add that, because you're interfacing with a legacy project with its own password hashing scheme, you can't simply use Laravel's built-in cryptography to hash passwords and handle authentication. – Chris Forrence Sep 06 '16 at 20:34
  • is true Auth::login($user); dont works yet but i feel close to resolve how to do that legacy thing and learn how things works in the proccess and later learn how to upgrade that but step by step – indian Sep 06 '16 at 20:46

1 Answers1

11

Instead of using mysql_* functions, you should use count() instead. It can be chained to Eloquent, query builder, or collections.

$users_count = DB::table('users')
     ->where('username', '=', $username)
     ->where('password', '=', $password)
     ->count();
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
cmnardi
  • 1,051
  • 1
  • 13
  • 27
  • u mean like that: $users = DB::table('users') ->where('username', '=', $username) ->where('password', '=', $password) ->get()->count(); ERROR:Call to a member function count() on array – indian Sep 06 '16 at 20:26
  • 1
    Note, @DevilSystem, that in cmnardi's answer, he's not chaining `get()`. – Chris Forrence Sep 06 '16 at 20:30
  • Pay attetion to your Laravel version too.. I think it don't change, but I'm not sure – cmnardi Sep 06 '16 at 20:44
  • 1
    @cmnardi Fortunately, `count()` has been around since at least [Laravel 4.2](https://laravel.com/docs/4.2/queries#aggregates) – Chris Forrence Sep 06 '16 at 20:49
  • `->count()` only works on collections, you have not returned a collection but an instance of the query builder. Updated your answer to reflect that. – Ohgodwhy Sep 06 '16 at 21:14
  • 1
    @Ohgodwhy, I rolled your edit back; the query builder does accept `count()` and other aggregate methods ([Source](https://laravel.com/docs/5.3/queries#aggregates)) – Chris Forrence Sep 07 '16 at 13:58
  • @ChrisForrence Good call! – Ohgodwhy Sep 07 '16 at 19:20