Laravel Not getting 404 errors - php

Hi there I'm having a problem with getting 404 error pages. At the moment all I get is a blank page with no data in it, Below is the code that I have in 3 different pages, I have my missing.blade.php page inside a folder called errors which is in the views folder, can someone tell me if I'm missing something else
// Routes file
App::error(function(ModelNotFoundException $e) {
return Response::view('errors.missing', array(), 404);
});
App::missing(function($exception) {
return Response::view('errors.missing', array(), 404);
});
// Error 404 Page
#extends('layouts.master')
#section('page-title') #parent
Error 404
#stop
#section('content')
<h1>An error occured 404, page missing</h1>
#stop
// Controller
public function edit($id)
{
$product = Product::findOrFail($id);
}

You will need to add your error handlers to
app/start/global.php

Related

calling a function before redirecting to 404 page on findOrFail

when i delete something from database ... lets say a blog , i might want to redirect the link for that blog to another link instead of 404 page
i have a table called setting_redirects :
setting_redirects : id , deleted_link , redirect_link
i'll store the deleted links and new link in this table
this is how i show a blog
function show( $blog_id ){
$blog = Blog::findOrFail($blog_id);
}
the problem is if it's not found findOrFail will automatically redirect user to 404 page ... i want to be able to checksetting_redirects to see if a redirect is available for that blog .... if so redirect to that new link otherwise go to 404
something like this
function show( $blog_id ){
$blog = Blog::find($blog_id);
if(!$blog)
{
$redirect_available = SettingRedirect::where('deleted_link ' , Request::url() ) ->first();
if($redirect_available )
return redirect( $redirect_available-> redirect_link );
else
abort(404);
}
}
but i want this for all my tables not only blogs and i dont want to write this code in all of my controllers
is there anyway to do this without changing all my controllers ? maybe a middleware before going to 404 page ?
findOrFail throws a ModelNotFoundException. I think you can simply catch and rethrow it.
try {
$blog = Blog::findOrFail($blog_id);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
$redirect_available = SettingRedirect::where('deleted_link', Request::url())->first();
if ($redirect_available)
return redirect($redirect_available->redirect_link);
throw $e;
}
Alternatively, you can put this logic in the app/Exceptions/Handler.php file inside the register() method.
<?php
namespace App\Exceptions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
class Handler extends ExceptionHandler
{
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
// this is to make sure the exception was caused by a findOrFail operation
if ($e->getPrevious() instanceof ModelNotFoundException) {
$redirect_available = SettingRedirect::where('deleted_link', $request->url())->first();
if ($redirect_available) {
return redirect($redirect_available->redirect_link);
}
}
});
}
}
The reason why the first line is $this->renderable(function (NotFoundHttpException $e, $request) { ... }) instead of$this->renderable(function (ModelNotFoundException $e, $request) { ... })
is because Laravel does this weird thing of transforming ModelNotFoundException into NotFoundHttpException before it's available to the exception handler.
I think need to change status of that particular record while deleting action, code on 404, if query executeble then include "mypage.php"; else would show default 404 page

Undefined variable in Laravel 8

I have issue with the undefined variable in Laravel 8, I actually don't understand why this happen because I was trying and playing with the Laravel 8.
I created the same method and same coding but somehow when I tried to run the coding for page about I got the error that said
ErrorException
Undefined variable: about (View: D:\Server\htdocs\app\resources\views\pages\about.blade.php)
Why is this happening ? I don't understand. Because I use the exact same coding for my other pages and it works but when I try to open the about page it suddenly give me the error when other pages are perfectly fine with no error.
PagesController
class PagesController extends Controller
{
public function index()
{
$title = "Welcome to my blog";
// return view ('pages.index', compact('title')); // first method
return view ('pages.index')->with('title',$title); // 2 method
}
public function about()
{
$about = "About Page";
return view ('pages.about')->with('about',$about);
}
public function services()
{
$data = array(
'title' =>'Services' // array
);
return view ('pages.service')-> with($data);
}
}
about.blade.php
#extends('layouts.app')
#section('content')
<h1>{{$about}} </h1>
<p> This is about pages </p>
#endsection
index.blade.php
#extends('layouts.app')
#section('content')
<h1>{{$title}} </h1>
<p> This is tutorial </p>
#endsection
Just to show you the same coding i use for index and about
My route if anyone asking
Route::get('/', [PagesController::class,'index']);
Route::get('/about', [PagesController::class,'about']);
Route::get('/services', [PagesController::class,'services']);
index.blade.php
about.blade.php
public function about ()
{
$ about = "About Page";
return view ('pages.about') -> compact ('about');
}
Replace it as is and try it: your error will be solved.
php artisan route:cache
Clearing the route cache helped me.
My variable was added later and data was output from the cache
for people still suffering from this issue , head over to web.php and make sure you dont have a duplicated route.

How to Custom 404 Page Not Found in CodeIgniter 4

I just learn CodeIgniter 4 Framework. How to customize my 404 page not found?
Go to your Routes.php file and find
$routes->set404Override();
Now , If you want to display just an error message then write
$routes->set404Override(function(){
echo "your error message";
});
instead of
$routes->set404Override();
Or
If you want to return a view then write like below:
$routes->set404Override(function(){
return view('your_filename');
});
instead of
$routes->set404Override();
// Would execute the show404 method of the App\Errors class
$routes->set404Override('App\Errors::show404');
// Will display a custom view
$routes->set404Override(function()
{
echo view('my_errors/not_found.html');
});
To customize your 404 page, modify app/Views/errors/html/error_404.php to your liking.
For custom error messages
in Config\routes.php
// Custom 404 view with error message.
$routes->set404Override(function( $message = null )
{
$data = [
'title' => '404 - Page not found',
'message' => $message,
];
echo view('my404/viewfile', $data);
});
in my viewfile, to display error:
<?php if (! empty($message) && $message !== '(null)') : ?>
<?= esc($message) ?>
<?php else : ?>
Sorry! Cannot seem to find the page you were looking for.
<?php endif ?>
from my controller:
throw new \CodeIgniter\Exceptions\PageNotFoundException('This is my custom error message');

Force a codeigniter custom 404

I have a custom 404 controller. It works fine. In routes.php I have:
$route['404_override'] = 'custom404';
this accesses this controller:
class custom404 extends MasterController {
public function __construct(){
parent::__construct();
}
public function index(){
$this->output->set_status_header('404');
$crit = array(
'subtype' => 'footer',
'status' => 'public'
);
$res = $this->mongo_db->where($crit)->get('contentobjects');
$this->pagedata = $res[0];
$this->load->view('404');
}
}
Can I call this from a different controller?
Currently I'm just forcing the issue by calling an (ostensibly) never-extant page:
if(!$this->viewable($res[0])){
header('Location: /404');
die;
}
Yes you can, just redirect to it directly.
However CI comes with an errors folder, with a sub folder for HTML and a 404 error view page. If you customize this page all your headers will be set correctly automatically, and you can call it in a much clearer manner.
if (empty($result))
{
// show error
show_error('The result you requested could not be found', '404');
}
Or more concisely:
if (empty($result)) show_error('The result you requested could not be found', '404');
The message here can be accessed in the template with $message field.
You can then easily set any code you need, like 401 etc.
http://www.codeigniter.com/user_guide/general/errors.html

How to detect missing parameter route and show relevant message

Working on Laravel 4, I created following route and able to fetch ID:
Route::get('details/{ID}', 'Exchange#details');
Issue is when I miss ID in route then it shows: NotFoundHttpException error. I want to avoid this. How do I proceed? Even in global.php I added following but did not work:
App::missing(function($exception)
{
print "Not Found";
// return Response::make(
// View::make('errors/404')
// , 404);
});
Controller Method
public function details($exchangeID)
{
echo "Print Details";
echo $exchangeID;
if(intval($exchangeID) == 0)
{
throw new NotFoundException;
}
}
Update: Recommendation of redirecting to 404 works but I am more interested to detect missing ID and load my Own View with proper message information instead of showing plain 404 page.
I would try something like this
# file routes.php
Route::get('{ID?}', 'SomeController#getDetails')
# file SomeController.php
function getDetails($ID=null) {
if empty($ID) {
return Redirect::to('PREVIOUS PAGE')
->withInput()
->with('error', 'invalid value');
}
}
Try like this :
App::missing(function($exception)
{
return View::make('errors.404');
});
The view is located in views/errors/404.blade.php

Categories