1. Use permission control in the controller
Use the laravel-Permission plug-in
/**
* PeopleController constructor.
*
* @param PersonRepository $repository
* @param PersonValidator $validator
*/
public function __construct(PersonRepository $repository, PersonValidator $validator)
{
$this->middleware(['permission:dagl_all|dagl_readonly']);
$this->repository = $repository;
$this->validator = $validator;
}
Copy the code
2, use,Gate
Determines whether permissions satisfy one of the given arrays
Gate::any(['dagl_all'.'dagl_readonly']);
Copy the code
3,API
User-friendly time display in
3.1, setCarbon
Chinese show
Add the following code to the boot function of App\Providers\AppServiceProvider
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot(a)
{
/ /...
// set Carbon to Chinese display
Carbon::setLocale('zh');
/ /...
}
/ /...
}
Copy the code
In 3.2,Model
To set the humanized display of the field. In order toArticle Model
的 created_at
Field as an example
use Carbon\Carbon;
public function getCreatedAtAttribute($date) {
if (Carbon::now() > Carbon::parse($date)->addDays(15)) {
return Carbon::parse($date);
}
return Carbon::parse($date)->diffForHumans();
}
Copy the code
$article->created_at; / / 1 seconds ago
Migrate 4path
parameter
php artisan migrate --path="database/migrations/2018_12_31_173608_create_settings_table.php"
Copy the code
5. Users can log out automatically if no operation stays too long
When writing a Web application, many people have encountered such a requirement: how to implement a user login after a long time (page no action or activity), we will automatically log out of the user login?
The solution is as simple as customizing Middleware in Laravel:
namespace App\Http\Middleware;
use Closure;
class SessionTimeout {
protected $timeout = 1200;
public function handle($request, Closure $next)
{ $isLoggedIn = $request->path() ! ='logout';
if(! session('lastActivityTime')){
app('session')->put('lastActivityTime', time());
} elseif(time() - app('session')->get('lastActivityTime') > $this->timeout){
app('session')->forget('lastActivityTime');
$cookie = cookie('intend', $isLoggedIn ? url()->current() : 'home');
$email = $request->user()->email;
auth()->logout();
return route('login')->withInput(['email' => $email])->withCookie($cookie);
}
$isLoggedIn ? app('session')->put('lastActivityTime', time()) : app('session')->forget('lastActivityTime');
return$next($request); }}Copy the code
We use lastActivityTime to determine if a user has done something (refreshing a page, visiting a new page, etc.), and if they haven’t done anything within 20 minutes, we jump to the login page.
6. Convert SimpleXMLElement to array
I met it when I was developing the flying pig order interface
$resp = $c->execute($req, $this->sessionKey);
/ / to obj
$obj = simplexml_load_string($resp->asXML());
$json = json_encode($obj);
// Get the array format
$respData = json_decode($json, true);
Copy the code
7. Logging
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\OperationLog;
use Illuminate\Support\Facades\Log;
class ApiOperationLog
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$input = $request->all();
/ / status code
$statusCode = $response->getStatusCode();
// Request parameters
$inputJson = json_encode($input, JSON_UNESCAPED_UNICODE);
// Returns content formatting
$responseJson = json_encode($response, JSON_UNESCAPED_UNICODE);
$uid = 0;
if(Auth::check()) {
$uid = (int) Auth::id();
}
$logLocal['uid'] = $uid;
$logLocal['path'] = $request->path();
$logLocal['method'] = $request->method();
$logLocal['ip'] = $request->ip();
$logLocal['input'] = $inputJson;
$logLocal['result'] = $response->original;
$logLocal['created_at'] = date('Y-m-d H:i:s');
$logLocal['http_code'] = intval($statusCode);
switch ($statusCode) {
// case '200':
// case '201':
// case '422':
// case '401':
// Log::info(json_encode($logLocal,JSON_UNESCAPED_UNICODE));
// break;
case '401':
case '422':
case '400':
case '500':
// Record to database
$logLocal['result'] = json_encode($response->original,JSON_UNESCAPED_UNICODE);
\DB::connection('mysql_log')->table('operation_log')->insert($logLocal);
break;
default:
Log::notice('Unknown status code:'.$statusCode);
break;
}
return$response; }}Copy the code
The sibling of paging returns with additional parameters
8. Use multiple mail servers for mail and add cc
/* * multiple mail configurations */
$toEmail = $request->get("email");
// backup current mail configs
$backup = Mail::getSwiftMailer();
// Setup your gmail mailer
$transport = new Swift_SmtpTransport(env('MO_MAIL_HOST'), env('MO_MAIL_PORT'), env('MO_MAIL_ENCRYPTION'));
$transport->setUsername(env('MO_MAIL_USERNAME'));
$transport->setPassword(env('MO_MAIL_PASSWORD'));
// Any other mailer configuration stuff needed...
$gmail = new Swift_Mailer($transport);
// Set the mailer as gmail
Mail::setSwiftMailer($gmail);
// Send your message
Mail::to($toEmail)->send((new OrderNotice($data))->subject("Please contact connoisseur holidays - Changhui International Travel LTD as soon as possible."));
// Restore your original mailer
Mail::setSwiftMailer($backup);
/* * add cc ->cc(array or string arg) */
$this->from(env('MO_MAIL_FROM_ADDRESS'), env('MO_MAIL_FROM_NAME'))
->cc(env('MO_MAIL_CC_ADDRESS'))
->markdown('emails.order.notice_mo_new');
Copy the code
- Stackoverflow.com/questions/2…
- Laravel.com/docs/7.x/ma…