1. 程式人生 > >laravel 輔助函式

laravel 輔助函式

 陣列&物件

1.array_divide()

array_divide 函式返回兩個陣列,一個包含原始陣列的健,另一個包含原始陣列的值
[$keys, $values] = array_divide(['name' => 'Desk']);
dd($keys, $values);

結果:

2.array_dot()

array_dot 函式將多維陣列平鋪到一維陣列中,該陣列使用「點」符號表示深度
$array = ['products' => ['desk' => ['price' => 100,'sum'=>10],'test'=>['price' => 1000,'sum'=>100]]];
$flattened = array_dot($array); dd($flattened);

結果:

3.array_except()

array_except 函式從陣列中刪除給定的鍵/值對
$array = ['name' => 'Desk', 'price' => 100];
$filtered = array_except($array, ['name']);
dd($filtered);

結果:

4.array_first()

array_first 函式返回陣列中第一個通過指定測試的元素
$array = [100, 200, 300];
$first
= array_first($array, function ($value, $key) { return $value >= 150; }); dd($first);

結果:

將預設值作為第三個引數傳遞給該方法。如果沒有值通過測試,則返回該值:$first = array_first($array, $callback, $default);

5.array_flatten()

array_flatten 函式將多維陣列平鋪為一維陣列
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby'=>'123']];
$flattened = array_flatten($array); dd($flattened)

結果:

6.array_forget()

array_forget 函式使用「點」符號從深度巢狀陣列中移除給定的鍵/值對
$array = ['products' => ['desk' => ['price' => 100]]];
array_forget($array, 'products.desk');
dd($array);
結果: 

7.array_get()

array_get 函式使用「點」符號從深度巢狀的陣列中檢索值
$array = ['products' => ['desk' => ['price' => 100]]];
$price = array_get($array, 'products.desk.price');
dd($price);
結果:

array_get 函式也接受一個預設值,如果沒有找到指定的健,則返回該值:
$discount = array_get($array, 'products.desk.discount', 0);

8.array_only()

array_only 函式僅返回給定陣列中指定的鍵/值對
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
$slice = array_only($array, ['name', 'price']);
dd($slice);
結果:

9.array_pluck()

array_pluck 函式從陣列中檢索給定鍵的所有值
$array = [
            ['developer' => ['id' => 1, 'name' => 'Taylor']],
            ['developer' => ['id' => 2, 'name' => 'Abigail']],
        ];
$names = array_pluck($array, 'developer.name');
dd($names);
 

結果:

你也可以指定生成的列表的鍵

$array = [
            ['developer' => ['id' => 2, 'name' => 'Taylor']],
            ['developer' => ['id' => 1, 'name' => 'Abigail']],
        ];
$names = array_pluck($array, 'developer.name','developer.id');
dd($names);

結果:

10.array_pull()

array_pull 函式返回並從陣列中刪除鍵/值對
$array = ['name' => 'Desk', 'price' => 100];
$name = array_pull($array, 'name');
dd($name,$array);
 

結果:

將預設值作為第三個引數傳遞給該方法。如果鍵不存在,則返回該值

$value = array_pull($array, $key, $default);

11.array_random()

array_random 函式從陣列中返回一個隨機值
$array = [1, 2, 3, 4, 5];
$random = array_random($array);
dd($random);

結果:

你也可以指定要返回的隨機數的數量作為第二個可選引數。一旦你指定了第二個引數,即使數量為 1,這個函式也會返回一個數組
$array = [1, 2, 3, 4, 5];
$random = array_random($array,3);
dd($random);

結果:

12.array_where()

array_where 函式使用給定的閉包來過濾陣列
$array = [100, '200', 300, '400', 500];
$filtered = array_where($array, function ($value, $key) {
            return is_string($value);
        });
dd($filtered);

結果:

13.data_get()

data_get 函式使用「點」符號從巢狀陣列或物件中檢索值
$data = ['products' => ['desk' => ['price' => 100]]];
$price = data_get($data, 'products.desk.price');
dd($price);

結果:

data_get 函式還接受預設值作為第三個引數,如果找不到指定的鍵,將返回該值

$discount = data_get($data, 'products.desk.discount', 0);

14.head() 函式返回給定陣列中的第一個元素

15.last() 函式返回給定陣列中的最後一個元素

16.app_path() 

app_path 返回 app 目錄的完整路徑。你還可以使用 app_path 函式來生成相對於 app 目錄的檔案完整路徑
$path = app_path();
dd($path);

$path = app_path('Http\Controllers\Controller.php');
dd($path);

17.base_path() 

base_path 函式返回專案根目錄的完整路徑。你還可以使用 base_path 函式生成指定檔案相對於專案根目錄的完整路徑
$path = base_path();
dd($path);

$path = base_path('vendor\bin');
dd($path);

18.config_path()  config_path 函式返回應用程式 config 目錄的完整路徑。你也可以使用 config_path 函式來生成應用程式配置目錄中給定檔案的完整路徑

19.database_path()  database_path 函式返回應用程式 database 目錄的完整路徑。你也可以使用 database_path 函式來生成資料庫目錄中給定檔案的完整路徑

20.public_path()  public_path函式返回應用程式 public目錄的完整路徑。你也可以使用 public_path函式來生成public目錄中給定檔案的完整路徑

21.resource_path()  函式返回應用程式 resource目錄的完整路徑。你也可以使用 resource_path函式來生成resource目錄中給定檔案的完整路徑

21.storage_path()  函式返回應用程式 storage目錄的完整路徑。你也可以使用 storage_path函式來生成storage目錄中給定檔案的完整路徑

 

字串

1.preg_replace_array()

preg_replace_array 函式使用陣列順序替換字串中的給定模式

$string = 'The event will take place between :start and :end';
$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);
dd($replaced);

結果:

2.str_random()

str_random 函式生成一個指定長度的隨機字串。這個函式數用 PHP 的 random_bytes 函式
$random = str_random(30);
dd($random);

3.str_replace_array()

str_replace_array 函式使用陣列順序替換字串中的給定值
$string = '該活動將於 ? 至 ? 之間舉行';
$replaced = str_replace_array('?', ['8:30', '9:00'], $string);
dd($replaced);

URLs
action() action 函式為指定的控制器動作生成一個 URL。你不需要傳遞完整的控制器名稱空間。只需要傳遞相對於 App\Http\Controllers 的名稱空間的控制器類名稱:
$url = action('[email protected]'); 如果該方法接受路由引數,則可以將它們作為方法的第二個引數傳遞: $url = action('[email protected]', ['id' => 1]);
asset() asset 函式使用當前請求的協議( HTTP 或 HTTPS )為資原始檔生成 URL:
$url = asset('img/photo.jpg');
secure_asset() secure_asset 函式使用 HTTPS 協議為資原始檔生成 URL
: $url = secure_asset('img/photo.jpg');
route() route 函式為給定的命名路由生成一個 URL:
$url = route('routeName'); 如果路由接受引數,則可以將它們作為方法的第二個引數傳遞: $url = route('routeName', ['id' => 1]); 預設情況下,route 函式生成的是絕對 URL。如果你想生成一個相對 URL,你可以傳遞 false 作為第三個引數: $url = route('routeName', ['id' => 1], false);
secure_url() secure_url 函式為給定的路徑生成一個標準的 HTTPS URL:
$url = secure_url('user/profile'); $url = secure_url('user/profile', [1]);
url() url 函式生成給定路徑的標準 URL:
$url = url('user/profile'); $url = url('user/profile', [1]); 如果沒有提供路徑,則返回 Illuminate\Routing\UrlGenerator 例項: $current = url()->current(); $full = url()->full(); $previous = url()->previous();
其他 abort() abort 函式丟擲 異常處理 程式呈現的 HTTP 異常: abort(
403); 你也可以提供額外的響應文字和自定義響應標頭: abort(403, 'Unauthorized.', $headers); abort_if() 如果給定的布林表示式計算結果為 true, abort_if 函式將丟擲一個 HTTP 異常: abort_if(! Auth::user()->isAdmin(), 403); 和 abort 方法一樣,你也可以提供異常的響應文字作為第三個引數,並提供一個自定義響應頭陣列作為第四個引數。 abort_unless() 如果給定的布林表示式計算結果為 false,abort_unless 函式將丟擲一個 HTTP 異常: abort_unless(Auth::user()->isAdmin(), 403); 和 abort 方法一樣,你也可以提供異常的響應文字作為第三個引數,並提供一個自定義響應頭陣列作為第四個引數。 app() app 函式返回 服務容器 例項: $container = app(); 你可以傳遞一個類或介面名稱來從容器中解析它: $api = app('HelpSpot\API'); auth() auth 函式返回一個 認證 例項。為了方便起見,你可以使用它來替代 Auth Facade: $user = auth()->user(); 如果需要,你可以指定你想要訪問的認證例項: $user = auth('admin')->user(); back() back 函式生成一個重定向 HTTP 響應到使用者之前的位置: return back($status = 302, $headers = [], $fallback = false); return back(); bcrypt() bcrypt 雜湊 使用 Bcrypt 對給定的值進行雜湊。你可以使用它替代 Hash facade: $password = bcrypt('my-secret-password'); broadcast() broadcast 函式將廣播給定的事件到它的監聽器: broadcast(new UserRegistered($user)); blank() blank 函式判斷給定的值是否為「空」: blank(''); blank(' '); blank(null); blank(collect()); // true blank(0); blank(true); blank(false); // false 要使用與 blank 相反的功能,請看 filled 方法。 cache() cache 函式可以用來從快取中獲取值。如果快取中不存在給定的健,則返回一個可選的預設值: $value = cache('key'); $value = cache('key', 'default'); 你可以通過將一組鍵/值對傳遞給函式來將其新增到快取中。與此同時,你還應該傳遞有效的分鐘數或持續時間作為快取過期時間: cache(['key' => 'value'], 5); cache(['key' => 'value'], now()->addSeconds(10)); class_uses_recursive() class_uses_recursive 函式返回一個類使用的所有 traits,包括任何子類使用的 traits: $traits = class_uses_recursive(App\User::class); collect() collect 函式根據給定的陣列建立一個集合例項: $collection = collect(['taylor', 'abigail']); config() config 函式獲取配置變數的值。可以使用「點」語法訪問配置值,其中包括檔案的名稱和希望訪問的選項。如果配置選項不存在,則可以指定一個預設值並返回: $value = config('app.timezone'); $value = config('app.timezone', $default); 可以在執行時通過傳遞一組鍵/值對來設定配置變數: config(['app.debug' => true]); cookie() cookie 函式建立一個新的 cookie 例項: $cookie = cookie('name', 'value', $minutes); csrf_field() csrf_field 函式生成包含 CSRF 令牌值的 HTMLhidden 表單欄位。例如,使用 Blade 語法: {{ csrf_field() }} csrf_token() csrf_token 函式獲取當前 CSRF 令牌的值: $token = csrf_token(); dd() dd 函式輸出給定的值並結束指令碼執行: dd($value); dd($value1, $value2, $value3, ...); 如果你不想終止指令碼執行,請改用 dump 函式。 decrypt() decrypt 函式使用 Laravel 的加密器來解密給定的值: $decrypted = decrypt($encrypted_value); dispatch() dispatch 函式將給定的任務推送到 Laravel 任務列隊中: dispatch(new App\Jobs\SendEmails); dispatch_now() dispatch_now 函式立即執行給定的任務,並從其 handle 方法返回值: $result = dispatch_now(new App\Jobs\SendEmails); dump() dump 函式列印給定的變數: dump($value); dump($value1, $value2, $value3, ...); 如果要在列印變數後停止執行指令碼,請改用 dd 函式。 encrypt() encrypt 函式使用 Laravel 的加密器對給定的值進行加密: $encrypted = encrypt($unencrypted_value); env() env 函式獲取環境變數的值或者返回預設值: $env = env('APP_ENV'); // 如果環境變數不存在則返回預設值... $env = env('APP_ENV', 'production'); {note} 如果在你在部署過程中執行 config:cache 命令,則應該保證只在配置中呼叫 env 函式。一旦配置被快取,.env 檔案則不會再被載入,所有對 env 函式的呼叫都將返回 null。 event() event 函式將給定的事件分派給它的監聽器: event(new UserRegistered($user)); factory() factory 函式根據給定的類、名稱和數量建立一個模型工廠構建器。可以在測試或資料填充中使用: $user = factory(App\User::class)->make(); filled() filled 函式判斷給定的值是否不為「空」: filled(0); filled(true); filled(false); // true filled(''); filled(' '); filled(null); filled(collect()); // false 要使用與 filled 相反的功能,請看 blank 方法。 info() info 函式將資訊寫入日誌: info('一些有用的資訊!'); 有前後關係的陣列也可以傳遞給函式: info('使用者登入嘗試失敗。', ['id' => $user->id]); logger() logger 函式可以將一個 debug 級別的訊息寫入到日誌中: logger('Debug 訊息'); 有前後關係的陣列也可以傳遞給函式: logger('User has logged in.', ['id' => $user->id]); 如果沒有傳值給函式則返回日誌的例項: logger()->error('You are not allowed here.'); method_field() method_field 函式生成一個 HTML hidden 表單欄位,其中包含表單的 HTTP 動作的欺騙值。例如,使用 Blade 語法: <form method="POST"> {{ method_field('DELETE') }} </form> now() now 函式為當前時間建立一個新的 Illuminate\Support\Carbon 例項: $now = now(); old() old 函式 獲取 會話中快閃記憶體的 舊輸入 值: $value = old('value'); $value = old('value', 'default'); optional() optional 函式可以接受任何引數,並且允許你訪問該物件的屬性或者呼叫方法。如果給定的物件是 null, 那麼屬性和方法會簡單地返回 null 而不是產生一個錯誤: return optional($user->address)->street; {!! old('name', optional($user)->name) !!} policy() policy 方法為給定的類獲取一個策略例項: $policy = policy(App\User::class); redirect() redirect 函式返回一個重定向 HTTP 響應,如果沒有沒有傳入引數,則返回重定向例項: return redirect($to = null, $status = 302, $headers = [], $secure = null); return redirect('/home'); return redirect()->route('route.name'); report() report 函式將使用異常處理程式的 report 方法丟擲異常: report($e); request() request 函式返回當前請求例項或者獲取輸入項: $request = request(); $value = request('key', $default); rescue() rescue 函式執行給定的閉包並捕獲執行期間發生的任何異常。所有被捕獲的異常將被髮送到你的異常處理程式的 report 方法。要注意的是,該請求將繼續處理: return rescue(function () { return $this->method(); }); 你也可以將第二個引數傳遞給 rescue 方法。如果在執行閉包時發生異常,這個引數將是應該返回的預設值: return rescue(function () { return $this->method(); }, false); return rescue(function () { return $this->method(); }, function () { return $this->failure(); }); resolve() resolve 函式使用服務容器將給定的類或介面名稱解析為其例項: $api = resolve('HelpSpot\API'); response() response 函式建立響應例項或者獲取響應工廠例項: return response('Hello World', 200, $headers); return response()->json(['foo' => 'bar'], 200, $headers); retry() retry 函式嘗試執行給定的回撥,直到到達給定的最大嘗試次數。如果回撥沒有丟擲異常,則返回值將被返回。如果回撥丟擲異常,它將自動重試。如果超過最大嘗試次數,則會丟擲異常: return retry(5, function () { // 在 100ms 左右嘗試 5 次... }, 100); session() session 函式可以用來獲取或者設定 Session 值: $value = session('key'); 你可以通過將一組鍵/值對傳遞給該函式來設定值: session(['chairs' => 7, 'instruments' => 3]); 如果沒有傳遞值給函式,則返回 Session 例項: $value = session()->get('key'); session()->put('key', $value); tap() tap 函式接受兩個引數:一個任意的 $value 和一個閉包。$value 將被傳遞給閉包,然後由 tap 函式返回。不需要在閉包中使用 return 返回值。 $user = tap(User::first(), function ($user) { $user->name = 'taylor'; $user->save(); }); 如果沒有閉包被傳遞給 tap 函式,你可以呼叫給定 $value 的任何方法。而你呼叫的方法的返回值始終為 $value ,無論方法在其定義中實際返回的是什麼。例如,Eloquent 的 update 方法通常會返回一個整數。但是,我們可以強制通過 tap 函式鏈式呼叫 update 方法來返回模型本身: $user = tap($user)->update([ 'name' => $name, 'email' => $email, ]); today() today 函式為當前日期建立一個新的 Illuminate\Support\Carbon 例項: $today = today(); throw_if() 如果給定的布林表示式計算結果為 true,throw_if 函式丟擲給定的異常: throw_if(! Auth::user()->isAdmin(), AuthorizationException::class); throw_if( ! Auth::user()->isAdmin(), AuthorizationException::class, 'You are not allowed to access this page' ); throw_unless() 如果給定的布林表示式計算結果為 false,則 throw_unless 函式會丟擲給定的異常: throw_unless(Auth::user()->isAdmin(), AuthorizationException::class); throw_unless( Auth::user()->isAdmin(), AuthorizationException::class, 'You are not allowed to access this page' ); trait_uses_recursive() trait_uses_recursive 函式返回一個類使用的所有 trait: $traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class); transform() 如果給定的值不為 blank 並且返回 Closure,那麼 transform 函式對給定的值執行 Closure 並返回其結果: $callback = function ($value) { return $value * 2; }; $result = transform(5, $callback); // 10 預設值或 Closure 也可以作為方法的第三個引數傳遞。如果給定值為空白,則返回該值: $result = transform(null, $callback, 'The value is blank'); // The value is blank validator() validator 函式用給定的引數建立一個新的驗證器例項。為方便起見,你可以使用它來代替 Validator facade : $validator = validator($data, $rules, $messages); value() value 函式返回給定的值。但是,如果將一個 Closure 傳遞給該函式,則將執行該 Closure 並返回其結果: $result = value(true); // true $result = value(function () { return false; }); // false view() view 函式獲取一個檢視例項: return view('auth.login');
with() with 函式會返回給定的值。如果傳入一個 Closure 作為該函式的第二個引數,會返回 Closure 執行的結果:
$callback = function ($value) { return (is_numeric($value)) ? $value * 2 : 0; }; $result = with(5, $callback); // 10 $result = with(null, $callback); // 0 $result = with(5, null); // 5