2017-09-14 108 views
0

enter image description here驗證具有相同的驗證功能的PHP laravel所有對象價值

以上爲對象的DD()一個的結果,現在我所做的是

//$car is a object variable 
$car->corporate_id = some_function($car->corporate_id); 
$car->corporate_name = some_function($car->corporate_name); 
$car->member_id = some_function($car->member_id); 

而不是做上述方式,我怎麼能達到像

$data = some_function($car); 
//it will go through all $car properties and run the same validation 

有人可以告訴我如何實現這一目標?

回答

0

我發現它, 第一的foreach的對象,例如$汽車爲對象,

foreach($cars as $car) 
{ 
    $carr = $car->map(function ($item, $key) 
      { 

       //code logic goes here 
       // $key variable is the index key of the object 
       // $item variable is value of the object 
       $data = $item + 1;   
       return $data ; 
      }); 

     //after this you can simply access the object attribute like usual 
     $carr->car_number; 
     $carr->car_name; 


} 

但是這是解決方案是使用laravel Collection,你也可以通過簡單調用將數組轉換爲集合

$collection = collect($anyArray); // make sure to include Illuminate\Support\Collection this class 
            //in order for to use the collection functionality 
1

函數體這樣

if(!is_object($car)) return 'function expect a car object'; 

if(isset($car->corporate_id)) 
    $car->corporate_id = some_other_function($car->corporate_id); 

if(isset($car->corporate_name)) 
    $car->corporate_id = some_other_function($car->corporate_name); 
........... 

return $car; 
+0

不,我期待al l對象屬性通過調用一個函數來運行相同的驗證函數,而不是像這樣一個一個地執行 –