Laravel Redirect To Another URL / Web Page - HTTP Laravel Redirects

Laravel Exception Handling Example Tutorial

Today, We want to share with you Laravel Exception Handling Example Tutorial For Beginners From Scratch.In this post we will show you Laravel MySQL query Exception Handling, hear for laravel catch exception in controller we will give you demo and example for implement.In this post, we will learn about Laravel Exceptions: How to Catch, Handle and Create Your Own with an example.

List of all Google Adsense, VueJS, AngularJS, PHP, Laravel Examples.

Laravel Exception Handling Example Tutorial For Beginners From Scratch

There are the Following The simple About Laravel Exception Handling Example Tutorial For Beginners From Scratch Full Information With Example and source code.

As I will cover this Post with live Working example to develop Exception Handling in Laravel, so the some major Laravel Exceptions for this example is following below.

  • MySQL query Exception Handling in Laravel
  • How to Laravel catch QueryException?
  • LARAVEL 5 EXCEPTION HANDLING Example
  • Debugging Queries in Laravel
  • ModelNotFoundException Exception handling
  • Laravel 404 Page Exceptions Handlers

Example 1 : MySQL query Exception Handling in Laravel

Handling sql based exceptions

try {
  $results = \DB::connection("atmiya25")
    ->select(\DB::raw("SELECT * FROM members"))
    ->first();
    // Closures include ->first() or ->get() or ->pluck(), etc.
} catch(\Illuminate\Database\QueryException $ex){
  dd($ex->getMessage());
  // Note any laravel controller method of class like PDOException can be called simple message on $ex.
}

Example 2 : How to Laravel catch QueryException?

Laravel MySQL query Exception Handling

    try {
        $this->model->create($data);

    } catch (Illuminate\Database\QueryException $e) {
        dd($e);

    } catch (PDOException $e) {
        dd($e);
    }

Example 3 : LARAVEL 5 EXCEPTION HANDLING Example

public function saveCreate()
    {
        $input = Input::all();
        try
        {
            $membersite = new MemberSite;
            $membersite->siteName = $input['siteName'];
            $membersite->description = $input['description'];
            $membersite->launchDate = $input['launchDate'];
            $membersite->save();


            MemberSite::where('siteName', $membersite->siteName)->first();
            $memberID = $membersite['memberID'];//getting memberID for use in join query

            $memberFeatures = DB::table('features')->join('memberFeatures', function ($join) use ($memberID)
            {
                $join->on('memberFeatures.featureID', '=', 'features.featureID')
                    ->where('memberFeatures.memberID', '=', $memberID);
            })->get();
            $groupIDs = [];
            foreach ($memberFeatures as $m)
                $groupIDs[] = $m->groupID;

            return View::make('profiles.memberProfiles')->with('membersite', $membersite)
                ->with('groupIDs', $groupIDs)
                ->with('memberFeatures', $memberFeatures);
        }
        catch (\Illuminate\Database\QueryException $e)
        {
            return View::make('edit.create')
                ->with('status', '<strong> Sorry, Your Website : ' . $siteName . ' Site already exist!</strong>');
        }
    }

Example 4 : Debugging Queries in Laravel

Example of the Simple Mysql Query Debugging in Laravel

$results = Member::where(function($q) use ($request) {
    $q->orWhere('member_email', 'like', '%[email protected]%');
    $q->orWhere('member_first_name', 'like', '%jaydeep%');
    $q->orWhere('member_last_name', 'like', '%Gondaliya%');
})->get();

Query exception Debugging

$results = Member::where(function($q) use ($request) {
    $q->orWhere('member_email', 'like', '%[email protected]%');
    $q->orWhere('member_first_name', 'like', '%jaydeep%');
    $q->orWhere('member_last_name', 'like', '%Gondaliya%');
})->toSql();
dd($results)

Listening For Mysql Query Events

\DB::listen(function($sql, $bindings, $time) {
    var_dump($sql);
    var_dump($bindings);
    var_dump($time);
});

Example 5 : ModelNotFoundException Exception handling

ModelNotFoundException

//ModelNotFoundException in Laravel
public function search(Request $request)
{
    try {
        $member = Member::findOrFail($request->input('member_id'));
    } catch (ModelNotFoundException $exception) {
        return back()->withError($exception->getMessage())->withInput();
    }
    return view('members.search', compact('member'));
}

Display an error in Blade view files

<h3 class="page-title text-center">Search for members by ID</h3>

@if (session('error'))
    <div class="demo-gst alert alert-danger">{{ session('error') }}</div>
@endif

Example 6 : Laravel 404 Page Exceptions Handlers

Creating A Laravel 404 Page Using Custom Exception Handlers

app/Exception/Handler.php

public function render($request, Exception $e)
{
// Laravel NotFoundHttpException
    if($e instanceof NotFoundHttpException)
    {
          return response()->view('errors.missing', [], 404);
    }
    return parent::render($request, $e);
}

Include On the Top first

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

resources/views/errors/404.blade.php

Laravel Create a 404 Page Not Found HTTP Error Exception Handler

<!DOCTYPE html>
<html>
<head>
    <title>Sorry - Page Not Found!. - Laravel 5 Create a 404 Page Not Found HTTP Custom Error Exception Handler</title>
</head>
<body>
<h1 class="huge">404</h1>
<hr class="well sm">
<p>You broke the balance of the internet</p>
<p>The page you are showing for was moved or deleted, removed, renamed<br>or might never you existed. You stumbled upon a any routers broken link :(</p>

</body>
</html>

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel Exception Handling Example Tutorial For Beginners From Scratch.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Count Query Codeigniter Tutorial
  2.   Laravel 7 Generate/Create PDF File Tutorial From Scratch
  3.   Laravel eloquent join with condition
  4.   IMPLODE() AND EXPLODE() FUNCTION IN PHP
  5.   Laravel 6 Get Config Variable Example - PHP
  6.   QueryException in laravel 6 Exception Handling
  7.   Laravel Vue JS ajax file upload multipart form data
  8.   php accelerator xampp install and/or enable
  9.   Angular 6 Reactive Forms Validation Tutorial Example
  10.   PHP Whatsapp Rest API Send and Recieve WhatsApp Message