Some Simple Practical Functions in laravel
- 2021-11-10 09:08:57
- OfStack
Preface
N When Laravel first came out years ago, it really made many people shine at the moment, and people exclaimed that the original PHP code could be written so concisely and elegantly.
This article mainly introduces some simple and practical functions about laravel, and shares them for everyone's reference and study. The following words are not much to say, let's take a look at the detailed introduction
Make dd () dump () of lumen as elegant as laravel1
composer require symfony/var-dumper
Gets the executed sql statement
You can view sql where parameters and so on
public function index()
{
DB::connection()->enableQueryLog(); // Open query log
DB::table('posts')->paginate(5); // To view sql
$queries = DB::getQueryLog(); // Get the query log
dd($queries); // You can view the executed sql Time of execution, parameters passed in, and so on
}
You can only see simple sql. You can't see the passed-in parameters
DB::table('posts')->toSql();
Query sql records
If you want to save the log file in the storage/logs directory. Need to be updated: boot () function in app/Providers/AppServiceProvider. php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use DB;
use Log;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
// Add code
DB::listen(function ($query) {
Log::info(
$query->sql,
$query->bindings,
$query->time
);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
Laravel How to Get the Value of a Field Before Modification in Model Events
Issue::saving(function(Issue $issue){
if ($issue->isDirty('title')) {
$user = Auth::user()->username;
$oldTitle = $issue->getOriginal('title'); // Original value
$newTitle = $issue->title; // New value
ActionLog::log("$user Put the title $oldTitle Modify to $newTitle");
}
});
Summarize