0

Here is my code

$string = str_random(20);
$get_token = DB::table('users')->select('token')-> get();

now I want to compare $string with $get_token . if it is not in database then it should add to database with the value $string has.

I have written this code.

if(strcmp($string , $get_token) !=0){
//add to DB
}

How can i compare my string to each of the string which is already in database.

Thank You

Bhavin Shah
  • 2,462
  • 4
  • 22
  • 35

2 Answers2

2

If you're using Models, you can run this code:

$token = str_random(20); //makes an random string with 20 characters
//select all tokens in the User model where token = $token and count it
$get_token = User::where('token', $token)->count(); //laravel returns an integer

if($get_token == 0) {
    //the token doesn't exist
    //Run the create token code
} else {
    //Token exist
}

Hope this works!


What are Models?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

More information: https://laravel.com/docs/5.2/eloquent

Robin Dirksen
  • 3,322
  • 25
  • 40
0

You can make a check in database if $string not exit then you can insert into database.

Take a look following code :

 $string = str_random(20);
 $get_token = DB::table('users')->where('token', '=', $string)->first();// get first record for that database.

 if(empty($get_token->token))
 {

 //if token not exit in database insert it into database.
  DB::table('users')->insert(
    array('token' =>$string )
  );

 }
Mohammad Sayeed
  • 2,025
  • 1
  • 16
  • 27
  • `$email_id = Input::get('email_id'); $api_token = str_random(50); if (User::where('api_token', '=', $api_token)->exists()) { $get_api_token = User::select('api_token') -> where('email_id', '=', $email_id) -> get(); } else{ DB::table('users')-> insertGetId(array( // insert new user in database 'email_id' => $email_id, 'api_token' => $api_token )); }` – Bhavin Shah Jul 04 '16 at 12:17
  • this is i want to do... if i get token which is exists in DB then return that token for given email id and if not then insert the token with given email_id – Bhavin Shah Jul 04 '16 at 12:17
  • what the error you are getting, its working for you or not ? – Mohammad Sayeed Jul 04 '16 at 12:28
  • `'<' unexpected ` in JSON – Bhavin Shah Jul 04 '16 at 12:33