laravel Model->save() does not throw database exception and i want to check unique constraint for a column (no primary key or other forign keys).
is there any way to get database error code of message when Model->save() return false?
You can try QueryException. to catch any SQL syntax or query errors.
use Illuminate\Database\QueryException
try {
$model = Model::find($id);
$model->name = 'joe';
$model->save();
} catch (QueryException $e) {
dd($e->getMessage());
}
You can use column "UNIQUE" in database , then error handle by QueryException.
=> If you have label exists, See below error:
"Exception message:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'TEST GO' for key 'materials_label_unique' (SQL: insert into `materials` (`label`, `updated_at`, `created_at`) values (TEST GO, 2019-08-27 09:53:47, 2019-08-27 09:53:47)) with code: 23000"
function insertMaterial()
{
try {
$material = new Materials;
$material->label = "TEST GO";
if( $material->save() ) {
return "True as a string";
} else {
return "False as a string";
}
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
=> If you'll try to find the non-existing record, See below error:
"Exception message: Creating default object from the empty value with code: 0"
function insertMaterial()
{
try {
$material = Materials::find(1111);
$material->label = "TEST GO";
if( $material->save() ) {
return "True as a String";
} else {
return "False as a String";
}
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
Related
I would like to know if it is possible to get the column name that made the duplicate error on an INSERT ?
For example, with an unique key on username and another unique key on email :
try{
$pdo->query("INSERT INTO `table`(`username`,`email`)`VALUES('Superman','xxx#xx.com')");
} catch (PDOException $e) {
if($e->errorInfo[0] == '23000' && $e->errorInfo[1] == '1062'){
throw new CustomException("Bla bla already exists");
// How does we get the duplicated column and then display "Email already exists" or "Username already exist"
} else {
throw $e;
}
}
How does we get the duplicated column info and then display "Email already exists" or "Username already exist" instead of "Duplicate entry (ok but which one?)
Thank you,
You can check value in db or grab colum name in the error message for your users.
try{
$pdo->query("INSERT INTO `table`(`username`,`email`) VALUES ('Superman','xxx#xx.com')");
} catch (PDOException $e) {
if (preg_match("/Duplicate entry .+ for key '(.+)'/", $e->getMessage(), $matches)) {
throw new CustomException($matches[1]." already exist");
} else {
throw $e;
}
}
also maybe you prefer to use exec command for "non result query string".
$affectedRow = $pdo->exec("INSERT INTO `table`(`username`,`email`) VALUES ('Superman','xxx#xx.com')");
Thanks for the idea. Didnt think that error could give me this info.
So it will result as this :
try {
$query = $this->dbh->prepare('INSERT INTO users (username,email) VALUES ("test", "test")');
$result = $query->execute();
} catch (PDOException $e) {
if( $e->errorInfo[0] == '23000' && $e->errorInfo[1] == '1062' ){
if( strpos($e->getMessage(), 'username') == true ) $result = 'duplicate_username';
elseif( strpos($e->getMessage(), 'email') == true ) $result = 'duplicate_email';
} else {
throw $e;
$return = false;
}
}
Basically doing the job.
Thanks,
So i started learning facebook sdk and i wanted to get attening_count/list from my event page as an array, but i'm unable to get it working. It only displays me id, name etc.
if (isset($_SESSION['access_tok'])) {
echo 'Out!<br>';
try {
$response = $fb->get('me/accounts?fields=', $_SESSION['access_tok']);
$page = $response->getGraphEdge();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
foreach($page as $pages)
{
$name = $pages['name'];
$cc = $pages['access_token'];
if($name == 'Testing')
{
try {
$response1 = $fb->get('/eventid', $cc);
$page1 = $response1->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$page1 ['id'];
}
else
{
}
}
}
I am not using any framework, i am developing myself... and i get that SQL error, the funny part is i get the error and the data/information still gets inserted but that error persists, i set user_id to accept null, then it moved to new_user_email
<?php
require_once("../private/initialize.php");
if (!$session->is_logged_in()) { redirect_to("login.php"); }
//if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//if (isset($_POST['submit'])) {
//$email_to = trim($_POST['email_to']);
/*$user = new User();
$user->setId($session->user_id);*/
//print_r($user->getId());
$invite_user = Invite::invite_by_mail($session->user_id, "rdweb#gmail.com");
if($invite_user) {
$invite_user->invite();
echo "Invite Sent";
}else{
echo "Invite Not Sent";
}
// }
//}
?>
i am setting the logged in user session id to the user_id which i wrote in the Invite class,
public static function invite_by_mail($user_id, $email_to="") {
if(!empty($user_id)) {
$invite = new Invite();
$invite->user_id = (int)$user_id;
$invite->new_user_email = $email_to;
$invite->token = Invite::generateToken();
return $invite;
} else {
return false;
}
}
public function invite()
{
$sql = "INSERT INTO invites (user_id, new_user_email, token, date_invited)
VALUES(:user_id, :new_user_email, :token, :date_invited)";
try {
// prepare sql an d bind parameters
$core = ConnectionManager::getInstance();
$stmt = $core->con->prepare($sql);
$user_id = $this->user_id;
$new_user_email = $this->new_user_email;
$token = $this->token;
$date_invited = strftime("%Y-%m-%d %H:%M:%S", time());
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->bindParam(':new_user_email', $new_user_email, PDO::PARAM_STR);
$stmt->bindParam(':token', $token, PDO::PARAM_STR);
$stmt->bindParam(':date_invited', $date_invited, PDO::PARAM_STR);
if ($stmt->execute()) {
$this->id = $core->con->lastInsertId();
echo "New Invite Recorded";
return true;
} else {
return false;
}
} catch (PDOException $e) {
//echo "Insert Error: " . $e->getMessage();
echo "DataBase Error: The user could not be added." . $e->getMessage();
}catch (Exception $e) {
echo "General Error: The user could not be added." . $e->getMessage();
}
}
i need help
this is the error i get
DataBase Error: The user could not be added.SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be nullNew Invite RecordedInvite Sent
and then it tells me invite sent and New invite added and populates the table
when i make sure the user_id table accepts Null from database, it the moves to new_user_email hence the error is now
DataBase Error: The user could not be added.SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'new_user_email' cannot be nullNew Invite RecordedInvite Sent
Invite Table
I'm having an issue catching the proper exception, no matter what i do i get the same response. This is the response i get in the view
Error validating access token: The user has not authorized application FacebookResponseException in FacebookResponseException.php line 89:
The issue arrises after a user de-authorizes my app from Facebook after have created an access_token , what I ant to do is catch the exception and automatically log them out and flush the session: But i can't seem to find the right exception to catch
I've tested with all these: I narrowed the problem to being inside this catch block: I included the catch block, then the full code I'm using in my route's function after.
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=permissions');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthenticationException $e) {
echo 'Facebook Dan1 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthorizationException $e) {
echo 'Facebook Dan2 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookClientException $e) {
echo 'Facebook Dan3 returned an error: ' . $e->getMessage();
exit;
} catch(Exception $e) {
echo 'Facebook Dan4 returned an error: ' . $e->getMessage();
exit;
}
now my full code for this page:
public function getHomeProfile(Request $request, LaravelFacebookSdk $fb)
{
$user = Auth::user();
$token = Session::get('fb_user_access_token');
$twitterToken = Session::get('access_token');
// $fb->setDefaultAccessToken($token);
// $resp = $fb->get('/debug_token?=input_token=$token');
// dd($resp);
$permissionsToRequest = ([
'public_profile',
'publish_actions'
]);
$login_link_for_public_actions = $fb->getLoginUrl($permissionsToRequest, 'http://pms.dev:8000/facebook/publicactions/callback');
if (isset($token)) {
$fb->setDefaultAccessToken($token);
// $debugToken = $fb->get('/debug_token?input_token=' . $token);
// $debugTokenResponse = $debugToken->getGraphNode()->asArray();
// echo "<pre>";
// print_r($debugTokenResponse);
// echo "<pre>";
// die();
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=permissions');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthenticationException $e) {
echo 'Facebook Dan1 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthorizationException $e) {
echo 'Facebook Dan2 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookClientException $e) {
echo 'Facebook Dan3 returned an error: ' . $e->getMessage();
exit;
} catch(Exception $e) {
echo 'Facebook Dan4 returned an error: ' . $e->getMessage();
exit;
}
// Returns a `Facebook\GraphNodes\GraphUser` collection
$facebookuser = $response->getGraphUser();
//$ty= json_decode($facebookuser);
$permissions = $facebookuser['permissions'];
$checked = '';
foreach ($permissions as $p) {
if ($p['permission'] == 'publish_actions' && $p['status'] == 'granted' ) {
$checked = 'checked';
}
}
} else {
$checked = null;
}
if (isset($twitterToken)) {
$twitterChecked = 'checked';
} else {
$twitterChecked = null;
}
$userPlugsCountry = $user->plugsCountry()->setPath($request->url());
$user_plugs_list = Auth::user()->plugs()->lists('id');
if (Auth::check()) {
$statuses = Status::where(function($query) {
return $query->where('user_id', Auth::user()->id)->where('parent_id', NULL)
->orWhereIn('user_id', Auth::user()->plugs()->lists('id'));
})->orderBy('created_at', 'desc')->paginate(7);
}
if (array_key_exists('REQUEST_SCHEME', $_SERVER)) {
$cors_location = $_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["SERVER_NAME"] .
dirname($_SERVER["SCRIPT_NAME"]) . "/cloudinary_cors.html";
} else {
$cors_location = "http://" . $_SERVER["HTTP_HOST"] . "/cloudinary_cors.html";
}
if ($request->ajax()) {
return [
'statuses' => view('ajax.status')->with('user', $user)->with(compact('statuses'))->render(),
'next_page' => $statuses->nextPageUrl(),
'countries' => view('ajax.next_countries')->with('user', $user)->with(compact('userPlugsCountry'))->render(),
'next_countries_page' => $userPlugsCountry->nextPageUrl(),
'prev_countries_page' => $userPlugsCountry->previousPageUrl(),
];
}
return view('profile.home')->with('user', $user)->with('cors_location', $cors_location)->with('statuses',$statuses)->with('userPlugsCountry',$userPlugsCountry)->with('checked', $checked)->with('login_link_for_public_actions',$login_link_for_public_actions)->with('twitterChecked', $twitterChecked);
}
OK i figured out whet i was doing wrong. I'm using sammyk laravelfacebooksdk https://github.com/SammyK/LaravelFacebookSdk and was only including:
use SammyK\LaravelFacebookSdk\LaravelFacebookSdk;
I didn't realize i also needed to add
use Facebook;
to the namespace.
easy fix, that gave me a lot of trouble.
I have an exception class that looks like this
<?php
class Errors{
public function displayError(Exception $e){
$trace = $e->getTrace();
if($trace[0]['class'] != ""){
$class = $trace[0]['class'];
$method = $trace[0]['function'];
$file = $trace[0]['file'];
$line = $trace[0]['line'];
$error_message = $e->getMessage().
"<br /> Class/Method : ".$class." <==> ".$method.
"<br /> File : ".$file.
"<br /> Line : ".$line;
}
return $error_message;
}
}
?>
This works fine for many errors that are thrown due do typos/column count not matching value count, but when I throw an exception from the code myself, I get an error. For example
try{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
$stmt->execute();
if ($stmt->rowCount() < 1){
throw new Exception('The Link expired, request a new one');
} else {
throw new Exception('The Link is invalid, please request a new one');
}
}
catch (PDOException $e) {
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
I get Uncaught exception 'Exception' with message 'The Link is invalid, please request a new one' error when I run the code. If I remove that line, and induce an error by spelling SELECT as SLECT, the error class works fine.
How can I make in such a way that the error class will catch all types of errors ?
The problem is NOT all exceptions are PDOExceptions.You code cacthes only PDOException which means new Exception won't be catched. Try :
try
{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
...
}
catch (PDOException $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
catch (Exception $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
The reason why your code works when you spell SELECT as SLECT is because you triggered a PDOException instead of a new Exception.