laravel上传文件

开发一个Web系统,上传文件是避免不了的,这在Laravel中实现非常简单,代码如下:

public function upload(Request $request)
{
    if ($request->hasFile('file')) {
        $file = $request->file('file');
        $fileName = Carbon::now()->timestamp . '.' . $file->getClientOriginalExtension();
        $destinationPath = 'uploads';
        $file->move($destinationPath, $fileName);
        return response()->json(['code'=>0, 'msg'=>'上传成功!', 'data'=>[
            'guarantee_file' => $fileName,
            'originalName' => $file->getClientOriginalName(),
        ]]);

        
    }

    return response()->json(['code'=>-1, 'msg'=>'请选择文件']);
}

表单不要忘记添加: enctype="multipart/form-data" 

Laravel中使用验证码

在Laravel中如果需要验证码,可以使用mews/captcha库来实现,过程如下 :

安装:

composer require "mews/captcha"

发布配置文件:

php artisan vendor:publish

前端引用:

<img src="{{captcha_src()}}" style="cursor: pointer" onclick="this.src='{{captcha_src()}}'+Math.random()">

注意,项目路径不能有中文,否则会报错:ErrorException: imagettfbbox(): Could not find/open font

简单吧,这就是生态强大的好处。

laravel下载apk文件

好像下载这个apk文件需要专门的headers,代码如下:

public function download(Request $request)
{
    $headers = [
        'Content-Type'=>'application/vnd.android.package-archive',
        'Content-Disposition'=> 'attachment; filename="android.apk"',
    ];
    return response()->download(public_path('apk/app.apk'), 'app.apk', $headers);
}

Laravel批量删除

有时,客户端会提交过来一些ID,需要删除这些ID对应的数据,代码如下:

public function destroy(Request $request): JsonResponse
{
    $customs = $request->collect();
    Custom::whereIn('id', $customs->pluck('id'))->delete();

    return response()->json(['code'=>0, 'msg'=>'删除成功!']);
}

Laravel打印Eloquent生成的完整SQL

开发调试中,经常需要查看Eloquent生成的SQL语句,以便排查错误,具体做法如下:

引入:use Illuminate\Support\Facades\DB;

DB::connection()->enableQueryLog(); // 开启QueryLog

$workLogs = WorkLog::where(function ($query) use ($request) {
    if ($request->has('keyword')) {
        $query->where('content', 'like', "%{$request->keyword}%");
    }
    if ($request->has('department_id')) {
        $query->with('user', function($userQuery) {
            $userQuery->where('department_id', $request->department_id);
        });
    }
})->orderByDesc('created_at')->paginate();

dd(DB::getQueryLog());

Laravel中ajax请求与csrf-token

Laravel中为了安全,请求会附带上csrf-token,当然也可以暴力的在VerifyCsrfToken中间件中排除项填写“*”以全局禁用,不过为了安全,这不是推荐的做法。

对于ajax请求,当然也需要带上csrf-token,具体做法如下:

在header中添加:

<meta name="csrf-token" content="{{ csrf_token() }}" />

然后在JS中添加:

<script type="text/javascript">
  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });
</script>

然后ajax就可以无感使用csrf了。

Laravel命名规范

路由:

URL:对于超过一个单词的情况,使用破折号-

路由名称:

超过一个单词,使用下划线:

例如:

Route::post('product-details/fetch', 'ProductDetailController@fetch')->name('product_details.fetch');

对于视图文件夹,超过连个单词,可以使用下划线:

views/master_products/xxx.blade.php

对于视图文件,使用短横线-,例如

show-filtered.blade.php

合起来就是:

views/master_products/show-filtered.blade.php

更多规范可以参考:https://github.com/alexeymezenin/laravel-best-practices/blob/master/chinese.md

后记:

不管是否采用该规范,最重要的是风格统一,没有什么标准,自己写的舒服,风格统一就是标准!