輔助函數


  • 輔助函數
  • 簡介

可用方法

#簡介

Laravel 包含各種各樣的「全域」PHP 輔助函數,框架本身也大量的使用了這些功能函數;如果你覺的方便,你可以在你的應用中任意使用這些函數

#########可用方法#########

陣列 & 物件

Arr::add
Arr::collapse
Arr::divide
##Arr::點##Arr::除了
##Arr::first
#Arr::展平
##Arr::忘記
#Arr::get
##Arr::有
#Arr : :last##Arr::only
#Arr::pluck
##Arr::prepend
# Arr::拉
##Arr::隨機##Arr::設定
#Arr::排序
##Arr::sortRecursive
#Arr::where
##Arr::wrap
#data_fill
#data_get
##data_set##head
last

##路徑
app_path
##base_path

#config_path

#database_path

##############

字串

__
#Str::camel
##class_basename
# # e##Str::endsWith
#Str::kebab
##preg_replace_array
Str::snake
Str::startsWith
##Str::after
Str::before
#Str::包含
#Str::finish##Str::is
Str::limit
#Str ::orderedUuid
##Str::plural
##Str::random
#Str::replaceArray# # Str::replaceFirst
##Str::replaceLast
##Str::單數
#Str::slug# #Str::start
##Str::studly
##Str::title
#trans
# trans_choice##Str::uuid

#URLs
##action



asset##secure_asset
##route
secure_url
url

#

其他

abort
abort_if
abort_unless
app







auth
back
bcrypt
blank
broadcast
#cache
class_uses_recursive
#collect
config
cookie
csrf_field
csrf_token
#dd
decrypt
dispatch
dispatch_now
dump
encrypt
env
event
factory
filled
info
logger
method_field
#now
old
optional
policy
redirect
report
request
rescue
resolve
response
retry
session
tap
today
throw_if

throw_unless

trait_uses_recursive

transform

##validator

#value

view

with

方法清單

陣列& 物件

############################ ###Arr::add()#########如果給定的鍵不存在數組中,那麼###Arr::add### 函數將會把給定的鍵/值對新增至陣列:###
use Illuminate\Support\Arr;
$array = Arr::add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
#########################Arr::collapse()########### #Arr::collapse### 函數將多個數字組合並為一個陣列:###
use Illuminate\Support\Arr;
$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
##################

Arr::divide()

Arr::divide 函數傳回一個二維數組,一個值包含原始數組的鍵,另一個值包含原始數組的值:

use Illuminate\Support\Arr;
[$keys, $values] = Arr::divide(['name' => 'Desk']);
// $keys: ['name']  多维数组中的第0个值
// $values: ['Desk']  多维数组中的第1个值

#Arr::dot()

##Arr::dot()

Arr::dot 函數將多維數組中所有的鍵平鋪到一維數組中,新數組使用“.”符號表示層級包含關係:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
$flattened = Arr::dot($array);
// ['products.desk.price' => 100]

Arr::except()

#Arr::except 函數從陣列中刪除給定的鍵/值對:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100];
$filtered = Arr::except($array, ['price']);
// ['name' => 'Desk']

#Arr::first()

Arr: :first
函數傳回數組中通過指定測試的第一個元素:

use Illuminate\Support\Arr;
$array = [100, 200, 300];
$first = Arr::first($array, function ($value, $key) {
    return $value >= 150;
 });
 // 200
將預設值作為第三個參數傳遞給該方法, 如果數組中沒有值通過測試,則傳回預設值:
use Illuminate\Support\Arr;
$first = Arr::first($array, $callback, $default);

#Arr::flatten()

Arr:: flatten 函數將多維數組中數組的值取出平鋪為一維數組:
use Illuminate\Support\Arr;
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$flattened = Arr::flatten($array);
// ['Joe', 'PHP', 'Ruby']

:forget()

Arr::forget 函數使用「.」符號從深度嵌套的陣列中刪除給定的鍵/值對:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::forget($array, 'products.desk');
// ['products' => []]

Arr::get()

Arr::get

函數使用“.”符號從深度嵌套的數組中根據指定鍵檢索值:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
$price = Arr::get($array, 'products.desk.price');
// 100

Arr::get 函數也接受一個預設值,如果沒有找到特定的鍵,將返回預設值:
use Illuminate\Support\Arr;
$discount = Arr::get($array, 'products.desk.discount', 0);
// 0

#Arr::has()

##Arr ::has

函數使用「.」符號找出陣列中是否存在指定的一個或多個鍵:
use Illuminate\Support\Arr;
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
$contains = Arr::has($array, 'product.name');
// true
$contains = Arr::has($array, ['product.price', 'product.discount']);
// false

Arr::last()

Arr::last
函數傳回數組中通過指定測試的最後一個元素:
use Illuminate\Support\Arr;
$array = [100, 200, 300, 110];
$last = Arr::last($array, function ($value, $key) {  
  return $value >= 150;
 });
// 300

將預設值作為第三個參數傳遞給該方法,如果沒有值通過指定測試,則傳回該預設值:
use Illuminate\Support\Arr;
$last = Arr::last($array, $callback, $default);

Arr::only()

Arr::only

函數只傳回給定陣列中指定的鍵/值對:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
$slice = Arr::only($array, ['name', 'price']);
// ['name' => 'Desk', 'price' => 100]

#Arr::pluck()

#Arr::pluck
函數從陣列中擷取給定鍵的所有值:
use Illuminate\Support\Arr;$array = [
    ['developer' => ['id' => 1, 'name' => 'Taylor']],    
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
  ];
$names = Arr::pluck($array, 'developer.name');
// ['Taylor', 'Abigail']
###你也可以指定取得的結果的鍵:###
use Illuminate\Support\Arr;
$names = Arr::pluck($array, 'developer.name', 'developer.id');
// [1 => 'Taylor', 2 => 'Abigail']
##################

Arr::prepend()

Arr::prepend 函數將一個值插入到陣列的開始位置:

use Illuminate\Support\Arr;
$array = ['one', 'two', 'three', 'four'];
$array = Arr::prepend($array, 'zero');
// ['zero', 'one', 'two', 'three', 'four']

如果需要,你可以指定你插入值的鍵:

use Illuminate\Support\Arr;
$array = ['price' => 100];
$array = Arr::prepend($array, 'Desk', 'name');
// ['name' => 'Desk', 'price' => 100]

#Arr::pull()

Arr::pull 函數從陣列中傳回指定鍵的值並刪除此鍵/值對:

use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100];
$name = Arr::pull($array, 'name');
// $name: Desk
// $array: ['price' => 100]

預設值可以作為第三個參數傳遞給該方法,如果鍵不存在,則傳回該值:

use Illuminate\Support\Arr;
$value = Arr::pull($array, $key, $default);

#Arr::random()

Arr::random 函數從陣列中隨機傳回一個值:

use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 4 - (随机检索)

你也可以將回傳值的數量當作可選的第二個參數傳遞給該方法,請注意,提供這個參數會回傳一個數組,即使是你只需要一項:

use Illuminate\Support\Arr;
$items = Arr::random($array, 2);
// [2, 5] - (随机检索)

Arr: :set()

Arr::set 函數使用「.」符號在多維數組中設定指定鍵的值:

use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::set($array, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]

#Arr::sort()

#Arr::sort 函數根據陣列的值對陣列進行排序:

use Illuminate\Support\Arr;$array = ['Desk', 'Table', 'Chair'];
$sorted = Arr::sort($array);
// ['Chair', 'Desk', 'Table']

你也可以根據給定閉包傳回的結果對陣列進行排序:

use Illuminate\Support\Arr;$array = [
    ['name' => 'Desk'],    
    ['name' => 'Table'],    
    ['name' => 'Chair'],
  ];
$sorted = array_values(Arr::sort($array, function ($value) { 
   return $value['name'];
   })
  );
/*
    [
        ['name' => 'Chair'],
        ['name' => 'Desk'],
        ['name' => 'Table'],
    ]
*/

#Arr::sortRecursive()

Arr::sortRecursive 函數使用sort 函數對陣列進行遞歸排序:

use Illuminate\Support\Arr;$array = [
    ['Roman', 'Taylor', 'Li'],    
    ['PHP', 'Ruby', 'JavaScript'],    
    ['one' => 1, 'two' => 2, 'three' => 3],
   ];
$sorted = Arr::sortRecursive($array);
/*
    [
        ['JavaScript', 'PHP', 'Ruby'],
        ['one' => 1, 'three' => 3, 'two' => 2],
        ['Li', 'Roman', 'Taylor'],
    ]
*/

Arr::where()

Arr::where 函式使用給定閉包傳回的結果過濾陣列:

use Illuminate\Support\Arr;
$array = [100, '200', 300, '400', 500];
$filtered = Arr::where($array, function ($value, $key) {
    return is_string($value);
  });
// [1 => '200', 3 => '400']

#Arr::wrap()

Arr::wrap

函數將給定的值變成一個數組,如果給定的值已經是數組,則不改變:

use Illuminate\Support\Arr;
$string = 'Laravel';
$array = Arr::wrap($string);
// ['Laravel']
如果給定的值是空,則傳回一個空數組:
use Illuminate\Support\Arr;
$nothing = null;
$array = Arr::wrap($nothing);
// []

###############data_fill()################################################################################################## data_fill### 函數使用「.」符號在多維數組或物件內設定缺省值:###
$data = ['products' => ['desk' => ['price' => 100]]];
data_fill($data, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 100]]]
data_fill($data, 'products.desk.discount', 10);
// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]
###這個函數也接受星號「*」作為通配符,對應的填入目標:###
$data = [
    'products' => [     
       ['name' => 'Desk 1', 'price' => 100],        
       ['name' => 'Desk 2'],    
      ],
   ];
data_fill($data, 'products.*.price', 200);
/*
    [
        'products' => [
            ['name' => 'Desk 1', 'price' => 100],
            ['name' => 'Desk 2', 'price' => 200],
        ],
    ]
*/
# ##################

data_get()

data_get 函數使用「.」符號從多維數組或物件中檢索值

$data = ['products' => ['desk' => ['price' => 100]]];
$price = data_get($data, 'products.desk.price');
// 100

#data_get 函數也可以接收一個預設值,如果找不到指定的鍵,則傳回預設值:

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

這個函數也接受「*」作為通配符,它​​可以匹配數組或物件的任何鍵:

$data = [ 
   'product-one' => ['name' => 'Desk 1', 'price' => 100],    
   'product-two' => ['name' => 'Desk 2', 'price' => 150],
 ];
data_get($data, '*.name');
   // ['Desk 1', 'Desk 2'];

data_set()

data_set 函數使用“.”符號在多維數組或物件中設定一個值:

$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]

該函數也可以接收“*”通配符,對應的在指定鍵上設定值:

$data = [
    'products' => [   
         ['name' => 'Desk 1', 'price' => 100],        
         ['name' => 'Desk 2', 'price' => 150],    
       ],
    ];
data_set($data, 'products.*.price', 200);
/*
    [
        'products' => [
            ['name' => 'Desk 1', 'price' => 200],
            ['name' => 'Desk 2', 'price' => 200],
        ],
    ]
*/

預設情況下,所有現有值都會被覆寫, 如果你只希望設定不存在的值,你可以選擇false 作為第四個參數傳遞給該方法:

$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200, false);
// ['products' => ['desk' => ['price' => 100]]]

head()

head 函數傳回給定陣列中的第一個元素:

$array = [100, 200, 300];
$first = head($array);
// 100

last()

last 函數傳回給定數組中的最後一個元素:

$array = [100, 200, 300];
$last = last($array);
// 300

#路徑

##app_path()

app_path 函數傳回

app
目錄的完整路徑.你也可以使用
app_path

函數來設定應用程式app 目錄的完整路徑:

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

##base_path()

base_path
函數傳回專案根目錄的完整路徑.你也可以使用

base_path 函數來設定專案根目錄的完整路徑:
$path = base_path();
$path = base_path('vendor/bin');

##config_path( )

config_path

函數傳回config 目錄的完整路徑.你也可以使用

config_path
函數來設定應用程式
config

目錄中給定檔案的完整路徑:
$path = config_path();
$path = config_path('app.php');

database_path()

database_path

函數傳回database 目錄的完整路徑.你也可以使用

database_path
函式來設定
database

目錄中給定檔案的完整路徑:
$path = database_path();
$path = database_path('factories/UserFactory.php');

######################################################################## ########mix()############mix### 函數傳回版本化Mix 檔案的路徑:###
$path = mix('css/app.css');
########## ########

public_path()

public_path 函數傳回 public 目錄的完整路徑.你也可以使用public_path 函數來產生public 目錄中給定檔案的完整路徑:

$path = public_path();
$path = public_path('css/app.css');

resource_path()

resource_path 函數傳回resources 目錄的完整路徑.你也可以使用resource_path 函數來產生資源檔案中給定檔案的完整路徑

$path = resource_path();
$path = resource_path('sass/app.scss');

storage_path()

storage_path 函數傳回storage 目錄的完整路徑.你也可以使用storage_path 函數來設定儲存目錄下指定檔案的完整路徑:

$path = storage_path();
$path = storage_path('app/file.txt');

字串

__()

__ 函數使用你的本地化檔案來翻譯給定的翻譯字串或翻譯鍵:

echo __('Welcome to our application');
echo __('messages.welcome');

如果指定的翻譯字串或翻譯鍵不存在,__# 函數將傳回給定的值.所以,依照上面的例子,如果翻譯鍵 messages.welcome 不存在, __ 函數會將其直接傳回.

Str::camel()

The Str::camel method converts the given string to camelCase:
Str::camel 函數將給定字串「蛇式」轉換為camelCase“駝峰式」:

use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// fooBar

#class_basename()

##class_basename 函數傳回被刪除了命名空間的指定類別的類別名稱:

$class = class_basename('Foo\Bar\Baz');
// Baz

e()

e 函數將預設值為truedouble_encode 選項值改為false 來執行 PHPhtmlspecialchars 函數:

echo e('<html>foo</html>');
// <html>foo</html>

Str::endsWith()

Str::endsWith 函數判斷指定的字串是否以給定的值結尾:

$result = Str::endsWith('This is my name', 'name');
// true

Str::kebab()

Str::kebab 函式將給定的「駝峰式」字串轉換為kebab-case 「短橫式」字串:

use Illuminate\Support\Str;
$converted = Str::kebab('fooBar');
// foo-bar

#

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);
//  活动将在 8:30 至 9:00 之间进行

#Str::snake()

#Str::snake 函數將給定的字串轉換為snake_case「蛇式」:

use Illuminate\Support\Str;
$converted = Str::snake('fooBar');
// foo_bar

Str::startsWith()

#Str::startsWith 函數判斷給定的字串的開頭是否是指定值:

use Illuminate\Support\Str;
$result = Str::startsWith('This is my name', 'This');
// true

##Str::after()

Str::after 函數傳回字串中指定值之後的所有內容:

use Illuminate\Support\Str;
$slice = Str::after('This is my name', 'This is');
// ' my name'

Str::before()

Str::before 函數傳回在字串中指定值之前的所有內容:

use Illuminate\Support\Str;
$slice = Str::before('This is my name', 'my name');
// 'This is '

#Str::contains()

Str::contains 函數判斷給定的字串是否包含給定的值(區分大小寫):

use Illuminate\Support\Str;
$contains = Str::contains('This is my name', 'my');
// true

你也可以傳遞一個陣列形式的值來判斷字串中是否包含任何值:

use Illuminate\Support\Str;
$contains = Str::contains('This is my name', ['my', 'foo']);
// true

Str::finish()

#Str::finish 函數將給定的字串以給定的值結尾傳回(如果它尚未以給定值結尾):

use Illuminate\Support\Str;
$adjusted = Str::finish('this/string', '/');
// this/string/
$adjusted = Str::finish('this/string/', '/');
// this/string/

Str::is()

#Str::is 函數判斷給定的字串是否符合給定的模式。星號* 可以用來表示通配符:

use Illuminate\Support\Str;
$matches = Str::is('foo*', 'foobar');
// true
$matches = Str::is('baz*', 'foobar');
// false

#Str::limit()

Str::limit 函數按給定的長度截斷給定的字串:

use Illuminate\Support\Str;
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);
// The quick brown fox...

你也可以傳遞第三個參數來改變將被追加到最後的字串:

use Illuminate\Support\Str;
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
// The quick brown fox (...)

#Str::orderedUuid()

The

Str: :orderedUuid 方法有效率地產生一個可儲存在索引資料庫列中的「第一時間」 UUID:

use Illuminate\Support\Str;
return (string) Str::orderedUuid();

Str::plural()

Str::plural 函數將字串轉換為複數形式。這個函數目前只支援英文:

use Illuminate\Support\Str;
$plural = Str::plural('car');
// cars
$plural = Str::plural('child');
// children

你可以提供一個整數作為函數的第二個參數來檢索字串的單數或複數形式:

use Illuminate\Support\Str;
$plural = Str::plural('child', 2);
// children
$plural = Str::plural('child', 1);
// child

Str::random()

Str::random  函數產生一個指定長度的隨機字串。這個函數用PHP 的random_bytes 函數:

use Illuminate\Support\Str;
$random = Str::random(40);

Str::replaceArray()

Str::replaceArray 函數使用陣列順序取代字串中的給定值:

use Illuminate\Support\Str;
$string = 'The event will take place between ? and ?';
$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);
// The event will take place between 8:30 and 9:00

##Str::replaceFirst()

Str::replaceFirst  函數取代字串中給定值的第一個符合:

use Illuminate\Support\Str;
$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');
// a quick brown fox jumps over the lazy dog

Str::replaceLast()

Str::replaceLast 函數取代字串中最後一次出現的給定值:

use Illuminate\Support\Str;
$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');
// the quick brown fox jumps over a lazy dog

Str::singular()

Str::singular 函數將字串轉換為單數形式。函數目前僅支援英文:

use Illuminate\Support\Str;
$singular = Str::singular('cars');
// car
$singular = Str::singular('children');
// child

Str::slug()

#Str::slug 函數將給定的字串產生一個URL 友善的「slug」:

use Illuminate\Support\Str;
$slug = Str::slug('Laravel 5 Framework', '-');
// laravel-5-framework

Str::start()

Str::start 函數將給定值加到給定字串的開始位置(如果字串尚未以給定值開始):

use Illuminate\Support\Str;
$adjusted = Str::start('this/string', '/');
// /this/string
$adjusted = Str::start('/this/string', '/');
// /this/string

#Str::studly()

# #Str::studly

函數將給定的字串轉換為「變種駝峰命名」:

use Illuminate\Support\Str;
$converted = Str::studly('foo_bar');
// FooBar

# #Str::title()

Str::title

函數將給定的字串轉換為「首字母大寫」:

use Illuminate\Support\Str;
$converted = Str::title('a nice title uses the correct case');
// A Nice Title Uses The Correct Case

trans()

#trans
函數使用你的本機檔案轉換給定的翻譯密金鑰:###
echo trans('messages.welcome');
###如果指定的翻譯健不存在,則###trans### 方法會簡單地傳回給定的健。所以,就上面的範例而言,如果翻譯健不存在, ###trans### 方法會回傳 ###messages.welcome### 。 #####################

trans_choice()

trans_choice 函數根據詞形變化來翻譯給定的翻譯健:

echo trans_choice('messages.notifications', $unreadCount);

如果指定的翻譯健不存在, trans_choice 方法會簡單地傳回給定的健。所以,依照上面的例子,如果翻譯健不存在, trans_choice 方法會回傳 messages.notifications

Str::uuid()

Str::uuid 方法產生一個UUID(版本4):

use Illuminate\Support\Str;
return (string) Str::uuid();

#URLs

##action()

action

函數為指定的控制器動作產生一個URL 。你不需要傳遞完整的控制器命名空間。只需要傳遞相對於 App\Http\Controllers 命名空間控制器類別名稱:

$url = action('HomeController@index');
$url = action([HomeController::class, 'index']);

如果該方法接受路由參數,則可以將它們作為方法的第二個參數傳遞:

$url = action('UserController@profile', ['id' => 1]);

asset()

asset
函數使用目前請求的協定( HTTP 或HTTPS )為資源檔案產生URL :
$url = asset('img/photo.jpg');

您可以透過ASSET_URL

.env

檔案中設定變數來設定資產URL 主機。如果您在Amazon S3 等外部服務上託管資產,這將非常有用:

// ASSET_URL=http://example.com/assets 
$url = asset('img/photo.jpg'); 
// http://example.com/assets/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()

如果給定的布林表達式計算結果為trueabort_if 函數會拋出一個HTTP 例外:

abort_if(! Auth::user()->isAdmin(), 403);

abort 方法一樣,你也可以提供異常的回應文字作為第三個參數,並提供一個自訂回應頭資料作為第四個參數。

abort_unless()

如果給定的布林運算式計算結果為falseabort_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 實例。

$collection = collect(['taylor', 'abigail']);

config()

config# 函數取得configuration變數的值。可以使用「點」語法存取配置的值,其中包括檔案的名稱和存取的選項,如果存取的設定選項不存在,你可以指定一個預設值並且傳回這個預設值:

$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 令牌值的HTML 輸入表單欄位hidden 。例如,使用Blade 語法:

{{ csrf_field() }}

#csrf_token()

csrf_token 函數取得目前CSRF 令牌的值:

$token = csrf_token();

dd()

##dd

函數列印輸出給定的變數並且結束腳本運行:

dd($value);
dd($value1, $value2, $value3, ...);
如果你不停止執行腳本,那麼可以使用 

dump 函數。

decrypt()

##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# 函數。

{提示} 你可以使用Artisan 中的dump-server 命令攔截所有的dump 呼叫並將它們顯示在控制台視窗而不是瀏覽器中。

encrypt()

encrypt 函數使用Laravel 的加解密機制對給定的值進行加密:

$encrypted = encrypt($unencrypted_value);

env()

env 函數可以取得環境變數配置的值或傳回預設值:

$env = env('APP_ENV');// 返回 'production' 如果 APP_ENV 未设置的话...$env = env('APP_ENV', 'production');

{注意} 如果你在部署過程中執行了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

#blank 方法與 

filled

作用相反。

info()

info 函數將資訊寫入log:

info('Some helpful information!');
可以將上下文資料數組傳遞給此函數:

info('User login attempt failed.', ['id' => $user->id]);

##logger( )

###logger### 函數可以用來將###debug### 層級的訊息寫入log:###
logger('Debug message');
###可以將上下文資料數組傳遞給此函數:###
logger('User has logged in.', ['id' => $user->id]);
###如果不帶參數呼叫此函數,它將傳回logger 實例:###
logger()->error('You are not allowed here.');
#################

method_field()

method_field 行數產生包含模仿表單 HTTP 動作的 HTML  hidden 網域。下面的範例使用了Blade 語法:

<form method="POST">
    {{ method_field('DELETE') }}
</form>

#now()

now 函數根據目前時間建立一個新的Illuminate\Support\Carbon# 實例:

$now = now();

old()

old 函數取得刷入session 的舊的輸入值:

$value = old('value');
$value = old('value', 'default');

optional()

optional 函數接受任何參數,並允許你存取該物件上的屬性或呼叫其方法。如果給定物件為null,則屬性或方法將傳回null 而不是引發錯誤:

return optional($user->address)->street;
{!! old('name', optional($user)->name) !!}

optional 函數也接受閉包作為其第二個參數。如果第一個參數提供的值不是null,閉包將會被呼叫:

return optional(User::find($id), function ($user) {
    return new DummyUser;
  });

policy()

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();
  });
也可以為其傳遞第二個參數。這個參數將會作為執行閉包引發例外狀況時的「預設」值:

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 () {
    // Attempt 5 times while resting 100ms in between attempts...
   }, 100);

session()

session 函數用於取得或設定session 值:

$value = session('key');

可以傳遞鍵值對陣列來設定session 值:

session(['chairs' => 7, 'instruments' => 3]);

不帶參數呼叫此函數,則傳回儲存在session 中的值:

$value = session()->get('key');
session()->put('key', $value);

tap()

tap 函數接受兩個參數: 任意$value 和閉包。 $value 將會傳遞給閉包,並且被 tap 函數傳回。與閉包的回傳值無關:

$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 使用的全部trait:## #
$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);
########################transform()############transform### 函數執行基於(非###空### )給定值的###閉包###,並傳回###閉包### 的結果:###
$callback = function ($value) {
    return $value * 2;
  };
$result = transform(5, $callback);
// 10
###也可以傳遞一個預設值或## #閉包### 作為函數的第三個參數。如果給定的值為空時,傳回該值:###
$result = transform(null, $callback, 'The value is blank');
// The value is blank
###################

validator()

validator 函數根據指定的參數建立一個新的 驗證器 實例。方便起見可以用它來代替Validator facade:

$validator = validator($data, $rules, $messages);

##value()

value 函數傳回給定值。如果傳遞閉包 給此函數,將執行閉包 並傳回閉包呼叫的結果:

$result = value(true);
// true
$result = value(function () {
    return false;
  });
// false

##view()

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
這篇文章首發在

LearnKu.com
網站上。