分类 php 下的文章


class HandleInertiaRequests extends Middleware
{
    public function handle(Request $request, Closure $next)
    {
        $response =  parent::handle($request, $next);
        if($response->isRedirection()) {
            $redirectTo = $response->headers->get('Location');
            $host = data_get(parse_url(config('app.url')), 'host');
            Log::debug('redirect to: '. $redirectTo);
            $redirectHost = data_get(parse_url($redirectTo), 'host');
            if($host !== $redirectHost) {
                return Inertia::location($redirectTo);
            }
        }
        return $response;
    }
}

function buildOutputSheet(array $data, $title, array $columns)
{
       $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle($title);

        // write the cell header(the first row)
        $worksheet->fromArray([array_values($columns)], null, 'A1');
        // writing data
        foreach ($data as $row => $item) {
            foreach (array_keys($columns) as $col => $field) {
                $value = $item[$field];
                $worksheet->setCellValueByColumnAndRow($col + 1, $row + 2, $value);
            }
        }
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $filename = now()->format('Ymd-') . \Illuminate\Support\Str::random(6) . '.xlsx';
        // got the file store path.
        $file_path = storage_path("app/public") . "/$filename";
        // save to file.
        $writer->save($file_path);
}

trait class 的定义

namespace App\Library\Model;

use Illuminate\Contracts\Validation\Factory;

trait WithValidates
{

//    protected $rules = [];
//    protected $customMessages = [];
//    protected $customAttributes = [];

    /**
     * @param $validator
     *
     * @return array
     */
    public function validateWith($validator)
    {
        if (is_array($validator)) {
            $validator = $this->getValidator($this->attributes, $validator);
        }
        $validator->after(function ($validate) {
            return call_user_func('self::afterValidate', $validate);
        });
        return $validator->validate();
    }

    protected function getValidator($data, $rules = [], $messages = [], $customAttributes = [])
    {
        return $this->getValidationFactory()->make($data, $rules ?: [], $messages ?: [], $customAttributes ?: []);
    }

    /**
     * Get a validation factory instance.
     * @return Factory
     */
    protected function getValidationFactory()
    {
        return app(Factory::class);
    }

    /**
     * @param null $rules
     * @param null $messages
     * @param null $customAttributes
     *
     * @return array
     */
    public function validate($rules = [], $messages = [], $customAttributes = [])
    {
        $validator = $this->getValidator(
            $this->attributes,
            $rules ?: $this->rules,
            $messages ?: $this->customMessages,
            $customAttributes ?: $this->customAttributes
        );
        $validator->after(function ($validate) {
            return call_user_func('self::afterValidate', $validate);
        });
        return $validator->validate();
    }

    /**
     * @param $validator
     */
    protected function afterValidate($validator)
    {

    }

}

简单使用

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tooltip extends Model
{
    use WithValidates;
    protected $rules = [
        'category' => 'string|required|max:64',
        'field' => 'string|required|max:64',
        'index' => 'integer|nullable',
        'description' => 'string|nullable',
    ];

    protected $fillable = [
        'category',
        'field',
        'index',
        'description',
    ];
}

abstract class 的方式来使用

abstract class BasicModel extends Model
{
    use WithValidates;

    protected $perPage = 10;
    protected $rules = [];
    protected $customMessages = [];
    protected $customAttributes = [];
}

model file usage

namespace App;

use App\Library\Model\BasicModel;

class Tooltip extends BasicModel
{
    protected $rules = [
        'category' => 'string|required|max:64',
        'field' => 'string|required|max:64',
        'index' => 'integer|nullable',
        'description' => 'string|nullable',
    ];

    protected $fillable = [
        'category',
        'field',
        'index',
        'description',
    ];
}

地址:https://mirrors.aliyun.com/composer/index.html

使用 Composer 镜像加速有两种选项:

  • 选项一:全局配置,这样所有项目都能惠及(推荐);
  • 选项二:单独项目配置;

选项一、全局配置(推荐)

$ composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

选项二、单独使用

如果仅限当前工程使用镜像,去掉 -g 即可,如下:

$ composer config repo.packagist composer https://mirrors.aliyun.com/composer/

取消镜像

composer config -g --unset repos.packagist
composer config --unset repos.packagist

ResourceCollection 是用于处理 返回值为json的时候定义返回的集合的格式,集合内的单个元素可以使用 Illuminate\Http\Resources\Json\JsonResource 定义,或者直接在toArray中重新定义。

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return UserResource::collection(User::all());
});

// 如果定义了Collection 

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
}
// 新的写法
use App\User;
use App\Http\Resources\UserCollection;

Route::get('/users', function () {
    return new UserCollection(User::all());
});