• laravel 使用常见问题记录


    1、文件上传默认为storage目录,修改上传路径为public目录

    if (!preg_match('/.(jpg|jpeg|png|gif)$/', $fileName,$ext))
    return response()->json(['code' => -3, 'data' => '', 'msg' => '只能上传jpg|png|gif|jpeg格式文件'])
    // 移动到框架应用根目录/public/uploads/ 目录下
                $path  = $file->storeAs( date('Ymd'),uniqid().'.'.$ext[1]);
                if($path ){
                    return   response()->json(['code' => 0, 'data' => ['src' =>'/uploads/'.$path], 'msg' => '']);
                }else{
                    // 上传失败获取错误信息
                    return    response()->json(['code' => -1, 'data' => '', 'msg' => $file->getError()]);
                }
    

      配置storeAs方法文件存储位置:config/filesystem.php

    /*默认为local*/
     'default' => env('FILESYSTEM_DRIVER', 'local'),
    /*修改public_path为默认文件上传路径*/
    'disks' => [
    
            'local' => [
                'driver' => 'local',
                'root' => public_path('uploads'),
            ],
    .............
    

    2、 在控件方法中获取路由参数

         在routes/web.php设置参数

     
    Route::post('{uploadfile}', 'chatFileController@uploadImg')->where(['uploadfile'=>'^(img|file)$']);
    

     在自定义Controller获取路由参数

      

      //上传图片
        public function uploadImg(Request $request)
        {
          /*获取路由参数*/
           $fileType=$request->route('uploadfile');
    
         ............
    

    3、部分页面取消使用token验证

        在appHttpMiddlewareVerifyCsrfToken.php 中排除指定路由

      

        /**
         * The URIs that should be excluded from CSRF verification.
         *排除upload下的所有路由使用token验证
         * @var array
         */
        protected $except = [
           '/im/service/upload/*'
        ];
    

      

     4、自定登陆验证表

         修改conifg/auth.php

    /*增加自定义chat_service验证*/
    
    'guards' => [
           ................
    
            'chatService' => [
                'driver' => 'session',
                'provider' => 'chat_service',
            ],
    'providers' => [
         ........................
            'chat_service' => [
                'driver' => 'eloquent',
                'model' => AppModelsChatService::class,
            ]
    ChatService类:
    namespace AppModels;
    /*要完成验证必须引用User*/
    use IlluminateFoundationAuthUser as Authenticatable;
    class ChatService extends Authenticatable
    {
       protected  $table='ws_users';
       protected $primaryKey='id';
       protected  $hidden='password';
        //自动维护时间戳
        public $timestamps = false;
    }
    

      

       使用方法:

      

    /*登陆验证*/
      if(Auth::guard('chatService')->attempt($request_params))
            {
                return response()->json(['msg'=>'登陆成功','code'=>200,'data'=>'index']);
            }
    

    添加中间件验证AuthChatService文件:

      

    use IlluminateContractsAuthFactory as Auth;
    
    *检查当前用户是否登陆*/
    class AuthChatService
    {
        private  $auth;
    
        public function  __construct(Auth $auth)
        {
            $this->auth=$auth;
        }
      public function handle($request, Closure $next)
        {
            if (!$this->auth->guard('chatService')->check()) {
                return  redirect('im/service/login');
            }
            return $next($request);
        }
    
    }
    

    路由加入中间件验证,未通过转向登陆页面

      /*验证客户是否登陆*/
            Route::group(['middleware'=>'authChatService'],function ()
            {
                Route::get('index','chatIndexController@index')->name('service.index');
    }

     5、表单验证时以json数据返回错误信息

        

    namespace AppHttpRequests;
    
    use IlluminateFoundationHttpFormRequest;
    
    class AdminChatLoginRequest extends FormRequest
    {
    /*重写form验证失败,返回json*/ protected function failedValidation(Validator $validator) { throw new HttpResponseException(response()->json(['msg'=>$validator->errors()->first(),'code'=>'400'],200)); } }

      

  • 相关阅读:
    Java Web前后端分离的思考与实践
    JDBC剖析篇(1):java中的Class.forName()
    UVa1471
    Uva11572
    Uva11134
    Uva10755
    Floyd判圈法
    Java泛型-通配符的上限和下限问题
    Codeforces 384E-线段树+dfs序
    codeforcesRound378C-dfs+树状数组
  • 原文地址:https://www.cnblogs.com/fogwang/p/12217253.html
Copyright © 2020-2023  润新知