以上就是给各位分享Laravel——自定义404处理方式,其中也会对laravel自定义错误返回信息进行解释,同时本文还将给你拓展Laravel5.8做个知乎16——用户关注发送自定义的邮件通知、la
以上就是给各位分享Laravel —— 自定义 404 处理方式,其中也会对laravel自定义错误返回信息进行解释,同时本文还将给你拓展Laravel 5.8 做个知乎 16 —— 用户关注 发送自定义的邮件通知、laravel 8 自定义日志文件名、自定义目录、Laravel API 路由 - 404、Laravel API 路由器总是找不到 404,即使我可以看到 Laravel 索引页面等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:- Laravel —— 自定义 404 处理方式(laravel自定义错误返回信息)
- Laravel 5.8 做个知乎 16 —— 用户关注 发送自定义的邮件通知
- laravel 8 自定义日志文件名、自定义目录
- Laravel API 路由 - 404
- Laravel API 路由器总是找不到 404,即使我可以看到 Laravel 索引页面
Laravel —— 自定义 404 处理方式(laravel自定义错误返回信息)
Laravel 有自己的 404 处理方式及对应的页面
大多项目中都需要定义自己的 404 页面
有些时候 404 页面中有动态数据
本篇文章的使用 Laravel 9
一、自定义 404 页面
方案一、在 resources/views/errors/ 创建 404.blade.PHP 文件,
方案二、用命令发布模板,PHP artisan vendor:publish --tag=laravel-errors
再次访问不存在的路由时,就会显示自己定义的 404 内容。
二、404 添加动态数据
框架的异常处理都在 app/Exceptions/Handler.PHP 中。
继承了 vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.PHP 文件。
方案一、重写异常处理方法
找到渲染异常的方法,并重写
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; // 状态为 404 时。把 data 渲染到 404 页面 // 其他状态,按照自带的逻辑处理 public function render($request, Throwable $e) { if ($e instanceof NotFoundHttpException) { if (view()->exists($view = 'errors.404')) { return response()->view($view, [ 'data' => 'test', ], $e->getStatusCode(), $e->getHeaders()); } } return parent::render($request, $e); }
方案二、注册自定义的渲染闭包
在 register 方法中,添加自定义 404 渲染
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; public function register() { $this->reportable(function (Throwable $e) { // }); $this->renderable(function (NotFoundHttpException $e, $request) { if (view()->exists($view = 'errors.404')) { return response()->view($view, [ 'data' => 'test', ], $e->getStatusCode(), $e->getHeaders()); } }); }
再次访问不存在的路由,动态数据可以在 404 页面显示出来。
Laravel 5.8 做个知乎 16 —— 用户关注 发送自定义的邮件通知
1 新建频道
1.1 \app\Channels\SendcloudChannel.PHP
<?PHP /** * Created by PHPStorm. * User: SUN * Date: 2021/8/1 * Time: 3:42 */ namespace App\Channels; use Illuminate\Notifications\Notification; /** * 自定义channels */ class SendcloudChannel { public function send($notifiable, Notification $notification) { $message = $notification->toSendcloud($notifiable,$notification); } }
2 添加频道
2.1 \app\Notifications\NewUserFollownotinfication.PHP
<?PHP namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Mail; use Naux\Mail\SendCloudTemplate; use App\Channels\SendcloudChannel; class NewUserFollownotinfication extends Notification { use Queueable; /** * Create a new notification instance. * * @return void */ public function __construct() { // } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { // return ['mail']; //邮件通知 return ['database',SendcloudChannel::class]; //站内信 } public function toSendcloud($notifiable) { //模板地址 //https://www.sendcloud.net/email/#/sendAround/template $data = [ 'url' => url(config('app.url')), 'name' => Auth::guard('api')->user()->name ]; //test_template 邮件模板 $template = new SendCloudTemplate('zhihu_app_new_user_follow',$data); Mail::raw($template,function ($message) use ($notifiable){ $message->from(env('SEND_CLOUD_FROM'),'知乎管理员'); $message->to($notifiable->email); }); } public function toDatabase($notifiable) { return [ 'name'=> Auth::guard('api')->user()->name, ]; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { return (new MailMessage) ->line('The introduction to the notification.') ->action('Notification Action', url('/')) ->line('Thank you for using our application!'); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ // ]; } }View Code
3 添加邮件模板
laravel 8 自定义日志文件名、自定义目录
环境:基于 laravel8 ,不支持laravel 5
laravel自带的Log::info日志功能有限,只能单个文件记录或者按照日期记录。
实际开发过程中,经常需要按功能来记录日志。为了方便,使用Logger自定义封装一些日志功能。
Logs日志类生成环境中使用了,很稳定,暂未发现什么问题。
<?PHP
/**
* laravel的日志类不够用,根据项目日志习惯二次封装Monolog日志类
*/
namespace App\Utils;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class Logs
{
// 文件记录类型 1:文件目录/日期/文件名 2:所有日志一个文件夹
public function __construct()
{
}
/**
* @param $message
* @param array $data
* @param string $filename
* @param string $isDate 是否按月份分文件夹
*/
private static function _save($message, $data = [], $filename = 'log', $isDate = false)
{
$log = new Logger('mylog');
if (PHP_SAPI == 'cli') {
// 命令行访问脚本的,加一个cli标识和用户浏览器访问的区分开
$filename .= '_cli';
}
$filename = $filename . '.log';
if ($isDate) {
// 是否要按日显示
$path = storage_path('logs/' . date('Ym'));
} else {
$path = storage_path('logs/');
}
// 有时候运维没给号权限,容易导致写入日志失败
self::mkDirs($path);
$path = $path . '/' . $filename;
if (gettype($data) != 'array') {
$message .= " " . $data;
$data = [];
}
$microtime = microtime();
$message = '[' . substr($microtime, 0, 8) . '] ' . $message;// 记录毫秒时间
// finally, create a formatter
$formatter = new LineFormatter("[%datetime%] %message% %context%\n", "Y-m-d H:i:s");
$stream = new StreamHandler($path, Logger::INFO);
$stream->setFormatter($formatter);
$log->pushHandler($stream);
$log->info($message, $data);
}
public static function info($message, $data = [], $filename = 'info', $isDate = false)
{
self::_save($message, $data, $filename, $isDate);
}
public static function debug($message, $data = [], $filename = 'debug')
{
self::_save($message, $data, $filename, false);
}
/**
* @param $message
* @param array $data
* @param string $filename
*/
public static function error($message, $data = [], $filename = 'error')
{
// 错误日志不会太多,按单文件记录可以了,默认$isDate=false
self::_save($message, $data, $filename, false);
}
/**
* 给日志文件夹权限
* @param $dir
* @param int $mode
* @return bool
*/
public static function mkDirs($dir, $mode = 0777)
{
if (is_dir($dir) || @mkdir($dir, $mode)) {
return TRUE;
}
if (!self::mkdirs(dirname($dir), $mode)) {
return FALSE;
}
return @mkdir($dir, $mode);
}
public static function sql($file_name = 'sql', $is_date = false)
{
DB::listen(function ($sql) use ($file_name, $is_date) {
foreach ($sql->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$sql->bindings[$i] = "'$binding'";
}
}
}
$query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
$query = vsprintf($query, $sql->bindings);
Logs::info('sql:', $query, $file_name, $is_date);
});
}
}
在业务层调用:
// 按日 按文件名
Logs::info('A 数组',['a','b'],'order',true);
// 按文件名
Logs::info('A 数组',['a','b'],'order');
// 只有字符串
Logs::info('B 字符串');
// 记录下面的执行sql
Logs::sql();
// 输出:
// [2021-04-15 11:50:37] [0.627499] sql:select * from `user` where `mobile` = '' limit 1 []
生成日志文件
Laravel API 路由 - 404
这可能是因为您的控制器中的 findOrFail
方法之类的东西。尝试在控制器启动时 dd
并再次尝试向 Postman 请求。
Laravel API 路由器总是找不到 404,即使我可以看到 Laravel 索引页面
如何解决Laravel API 路由器总是找不到 404,即使我可以看到 Laravel 索引页面?
操作系统:windows server 2019
网络服务器:Apache
Laravel:8.46.0
我从我的另一台计算机上克隆了这个项目,另一台计算机正在安装 XAMPP 包。
这台电脑,我分别安装了apache、MysqL和PHP。
在另一台计算机上,所有 api url 都在工作。
我已经在 httpd.conf 中设置了虚拟主机,如下所示。
关于服务器名,我设置的是我的真实域名,不是这样的。
<VirtualHost *:80>
DocumentRoot "C:\Apache24\htdocs"
ServerName myDomainName
ErrorLog "C:\Apache24\htdocs\project_name_error.log"
CustomLog "C:\Apache24\htdocs\project_name_access.log" combined
DirectoryIndex index.PHP
<Directory "C:\Apache24\htdocs">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
当我用浏览器访问我的IP时,我可以看到laravel的索引页面。但是当我想输入一个api url时,它总是显示404 not found。为什么?
我正在尝试 api url 就像这三个:
http://domainName/project_name/public/api/
http://domainName/public/api/
http://domainName/api/
顺便说一句,在我的另一台电脑上,我可以输入第一个 url 来获取我的资源。
有什么建议吗?
谢谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
我们今天的关于Laravel —— 自定义 404 处理方式和laravel自定义错误返回信息的分享就到这里,谢谢您的阅读,如果想了解更多关于Laravel 5.8 做个知乎 16 —— 用户关注 发送自定义的邮件通知、laravel 8 自定义日志文件名、自定义目录、Laravel API 路由 - 404、Laravel API 路由器总是找不到 404,即使我可以看到 Laravel 索引页面的相关信息,可以在本站进行搜索。
本文标签: