Here with try and catch you can use Log to keep errors in records and you can check records in log section in application:
public function storestudent(Request $request)
{
try
{
$student= new student();
$student->sregno= $request['regno'];
$student->save();
return redirect('/home');
} catch(Exception e){
$error = sprintf('[%s],[%d] ERROR:[%s]', __METHOD__, __LINE__, json_encode($e->getMessage(), true);
\Log::error($error);
}
}
For more info for Log fascade check this link: Logging.
And another way is to handle exception custom exception handling which you can get here.Error handling
To show error messages on redirect simply use flash messages in laravel without custom exceptions need. following code:
public function storestudent(Request $request)
{
try
{
$student= new student();
$student->sregno= $request['regno'];
$student->save();
\Session::flash('message','Saved successfully');
return redirect('/home');// if you want to go to home
} catch(Exception e){
\Session::flash('error', 'Unable to process request.Error:'.json_encode($e->getMessage(), true));
}
return redirect()->back(); //If you want to go back
}
Flash messages:
@if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{
Session::get('message') }}</p>
@endif
or for more common flash view:
<div class="flash-message">
@foreach (['danger', 'warning', 'success', 'info','error'] as $msg)
@if(Session::has($msg))
<p class="alert alert-{{ $msg }}">{{ Session::get($msg) }}
</p>
@endif
@endforeach
</div>
Controller code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Candidate;
use App\student;
use Exception;
class Homecontroller extends Controller
{
//function for login page
public function insertReg()
{
return view('login');
}
public function storestudent(Request $request)
{
try {
if ( !student::where('sregno',$request->regno )->exists() ) {
$student= new student();
$student->sregno= $request->regno;
if ($student->save()) {
\Session::flash('message','Saved successfully');
return redirect('/home');// if you want to go to home
} else {
throw new Exception('Unable to save record.);
}
} else {
throw new Exception('Record alreasy exists with same sregno');
}
} catch(Exception $e){
\Session::flash('error', 'Unable to process request.Error:'.json_encode($e->getMessage(), true));
}
return redirect()->back(); //If you want to go back
}
Hope this helps.