I created dynamic sidebar menu and when I try to insert new menu I am getting error message Route [nameroute] is not defined. How do I handle this error with try catch ?
This is my controller file.
DB::beginTransaction();
try
{
$insert = AppMenu::insertGetId([
'description' => $request->description,
'menu_url' => $request->menu_url ? $request->menu_url:null,
'menu_alias' => $request->menu_alias ? $request->menu_alias:null,
'ismenu' => $request->ismenu,
'parent' => $request->parent ? $request->parent:null,
'menu_icon' => $request->menu_icon,
'menu_order' => $request->menu_order
]);
DB::table('appmenu_role')->insert([
'appmenu_id' => $insert,
'role_id' => $role
]);
}
catch (\InvalidArgumentException $e)
{
return Redirect::back()->with('infoMessage', "Route not defined. ");
}
DB::commit();
Session::flash('successMessage', 'Menu Created');
return Redirect('menu');
You should use Exception class to catch any kind of exception.
catch (\Exception $e)
{
return Redirect::back()->with('infoMessage', "Route not defined.");
}
Related
I'm creating new user after that sending notification to user, i don't want to send notifications if user not created whether server side error occurs or on failure of database query. I'm trying to use transaction, but do not have idea where to place transaction code so that if user not created then it should not move to next code block.
$save = new newUser;
if($save->save()){
// Notification block
return response()->json(['status' => true, 'title' => 'Created' , 'message' => 'Data Saved Successfully'],200);
}
else
{
return response()->json(['status' => false ,'title' => 'Error' , 'message' => 'Data Not Saved'],200);
}
Any help is highly appreciated
You can use continue & break in your if else Condition.
If they have user exist then continue otherwise break it.
If there is some error while saving the user, e.g. error in database insert query or some other error, then the $save->save() will throw an exception. So you can handle it like this:
try {
$save->save();
return response()->json(['status' => true, 'title' => 'Created' , 'message' => 'Data Saved Successfully'],200);
} catch (\Exception $e) {
report($e);
return response()->json(['status' => false ,'title' => 'Error' , 'message' => 'Data Not Saved'],200);
}
Furthermore, you can try to catch a particular exception and send an appropriate notification for that failure.
I have Laravel-5.8 project code:
public function store(StoreTypeRequest $request)
{
$userCompany = Auth::user()->company_id;
DB::beginTransaction();
try{
$data = Type::create([
'name' => $request->name,
'parent_id' => $request->parent_id,
'max_score' => $request->max_score,
'comment' => $request->comment,
]);
$data1 = DB::table('types')->select('max_score')->where('id', $request->parent_id)->where('company_id', $userCompany)->whereNull('parent_id')->first();
$data->update(['max_score1' => $data1->max_score]);
DB::commit();
Session::flash('success', 'Type is created successfully');
return redirect()->route('types.index');
} catch (Exception $exception)
{
DB::rollback();
Session::flash('error', 'Action failed! Please try again');
return back();
}
}
When I submitted, I got this error:
Action failed! Please try again
How do I make the application to show specific error, so that the user will be clear about what caused the error?
Thank you
Catch an exception on using try-catch statements :
Use Exception;
try
{
// write your codes here
}
catch(Exception $exception)
{
dd($exception->getMessage());
}
If you want to catch PDO Exception :
use PDOException;
try
{
//write your codes here
}
catch(PDOException $e)
{
dd($e->getMessage());
}
If above code isn't working then give a backslash \ before Exception & PDOException
I have error!!! Please help!!!
GuzzleHttp\Exception\ClientException : Client error: POST http://10.100.0.7:8080/eureka/apps/NewsService resulted in a 404 Not Found response
public function handle()
{
$client = new EurekaClient([
'eurekaDefaultUrl' => 'http://10.100.0.7:8080/eureka-
server/eureka',
'hostName' => 'NewsService',
'appName' => 'NewsService',
'ip' => '10.111.2.23',
'port' => ['8000', true],
]);
try {
$client->register();
$client->start();
} catch (Exception $e) {
return $e->getResponse();
}
}
Create laravel console command and use https://github.com/PavelLoparev/php-eureka-client
In Laravel 5.5 I am trying to handle an error exception like this...
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
}
catch(ModelNotFoundException $e) {
return Response::json(array(
'error' => true,
'status_code' => 400,
'response' => 'fruit_id not found',
));
}
But this is giving me a 'Trying to get propert of non-object' error
The same error handling works correctly for findorfail, how should I be doing this for the 'where' statement?
I think you are passing wrong values in your where query in the try block.
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
}
Is it fruit_id or just id because you are querying it on fruit model itself.
Thanks to some pointers in the comments I changed to
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
}
catch(\Exception $e) {
return Response::json(array(
'error' => true,
'status_code' => 400,
'response' => 'fruit_id not found',
));
}
All is now working now I am catching the correct exception
Tested on Laravel 5.7
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
}
catch(\Exception $e) {
abort(404);
}
Even though you got it working, I'd like to make mention of Laravel's Exception Handler.
The report method allows you to catch any exception type and customize how you wish to process and move forward. There is a report helper function as well which is globally accessible.
Furthermore, reportable and renderable exceptions allow you to create and customize your responses.
Try the below code:
if ($user->fruit) {
try {
$fruits = Fruit::where('fruit_id', $user->fruit->id)->get();
} catch(\Exception $e) {
return Response::json(array(
'error' => true,
'status_code' => 400,
'response' => 'fruit_id not found',
));
}
} else {
return "User Fruit doesn't exists!!";
}
I have a User model for basic user info, then a Role model and RoleUser model to associate roles with user. On user edit form, additional role can be added to that user. So, here two DB operations are done within a DB::transaction,
1) Update User info into User model
2) Add role to user
The issue is, if "Add role to user" fails, it doesn't Rollback changes in "User" model which already updated successfully.
Here is my sample code-
In Controller:
$response =
DB::transaction(function() use($user_data, $input) {
//Update changes in basic user info using "User" Model
$response = User::updateUser($user_data['user']);
if ($response->status===FALSE) {//not updated
return $response;
}
if (!empty($user_data['roles'])) {
$roles = [];
foreach ($user_data['roles'] as $role) {
$roles[] = ['role_id' => $role, 'user_id' => $user_data['user']['id'], 'created_by' => $this->curr_user->id, 'updated_by' => $this->curr_user->id];
}
//Add new roles to the user using "RoleUser" Model
$response3 = RoleUser::createRoleUser($roles);
if ($response3->status===FALSE) {//failed to add
return $response3;
}
}
return $response;
}, 5);
//source of createRoleUser method in RoleUser model
try {
DB::table($table)->where('id', $id)->update($changes);
} catch (\Illuminate\Database\QueryException $qe) {
return (object) ['status' => FALSE, 'error' => $qe->errorInfo];
} catch (\Exception $e) {
return (object) ['status' => FALSE, 'error' => [$e->getCode(), 'non-DB', $e->getMessage()]];
}
return (object) ['status' => TRUE, 'data' => $changes + ['id' => $id]];
//source of createRoleUser method in RoleUser model
try {
$new_rec_id = DB::table('role_users)->insertGetId($new_data);
$new_rec = FALSE;
if ($new_rec_id) {
$new_rec = DB::table($table)->where('id', $new_rec_id)->first();
}
} catch (\Illuminate\Database\QueryException $qe) {
return (object) ['status' => FALSE, 'error' => $qe->errorInfo];
} catch (\Exception $e) {
return (object) ['status' => FALSE, 'error' => [$e->getCode(), 'non-DB', $e->getMessage()]];
}
return (object) ['status' => TRUE, 'data' => $new_rec];
You have to throw an exception from within the transaction closure in order for the transaction to trigger the rollback. If no exception is thrown, the transaction will commit.
Keeping this in mind, that means the call to the transaction function needs to be wrapped in a try/catch, as the code that handles the rollback will rethrow the exception after the rollback for your application code to handle.
So, your code would look something like:
try {
$response = DB::transaction(function() use($user_data, $input) {
//Update changes in basic user info using "User" Model
$response = User::updateUser($user_data['user']);
if ($response->status===FALSE) {//not updated
// throw exception to trigger rollback
throw new \Exception($response->error);
}
if (!empty($user_data['roles'])) {
$roles = [];
foreach ($user_data['roles'] as $role) {
$roles[] = ['role_id' => $role, 'user_id' => $user_data['user']['id'], 'created_by' => $this->curr_user->id, 'updated_by' => $this->curr_user->id];
}
//Add new roles to the user using "RoleUser" Model
$response3 = RoleUser::createRoleUser($roles);
if ($response3->status===FALSE) {//failed to add
// throw exception to trigger rollback
throw new \Exception($response3->error);
}
}
// return without exception to trigger commit
return $response;
}, 5);
} catch (\Exception $e) {
echo 'uh oh: '.$e->getMessage();
}