# [Laravel][eloquent][Model]Model相關筆記 ###### tags: `laravel`,`eloquent`,`model` ## CRUD ### update #### 直接根據接收的用戶輸入json去update資料 ```php! $category = Category::find($request->input('id')); $fillable = collect($category->getFillable())->toArray(); $formField = $request->only($fillable); $category->update($formField); ``` ## model scope ### 範例:自訂搜尋 [參考連結](https://youtu.be/MYyJ4PuL4pY?t=6603) App/Models/Listing ```php= ... public function scopeFilterTag($query,array $filters){ // 這句很重要,不能只寫 if($filters['tag'](){,會出問題 if($filters['tag'] ?? false){ $query->where('tags','like','%'.request('tag').'%'); } } ``` app/Http/Controllers/ListingController.php ```php= public function index(Request $request){ return view('listings.index', [ 'listings' =>Listing::latest()->filterTag(request(['tag']))->get(), ]); } ``` ## eloquent ### 隱藏特定欄位(laravel 8 可用) ```php= return response()->json($user->makeHidden([ "email_verified_at", "created_at", "updated_at" ])) ``` ### 取得最後一筆資料 [參考連結](https://stackoverflow.com/questions/16549455/select-last-row-in-the-table) ```php= Contact::latest()->first() ``` ### 取得Model $fillable的值(laravel 8 可用) https://stackoverflow.com/questions/39859983/how-to-get-fillable-variable-as-array-in-laravel-4-2 ```php= (路徑看model檔在哪裡而修改,不一定都在App\Models\) $model = new App\Models\Demo; dd($model->getFillable()); ``` ## 取得table的欄位名稱 https://laravel-tricks.com/tricks/get-table-column-names-as-array-from-eloquent-model model ```php! use Illuminate\Database\Eloquent\Model; class SomeModel extends Model { public function getTableColumns() { return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable()); } } ``` ## 用別名取得table某欄位的值 https://stackoverflow.com/questions/26958080/how-to-alias-the-name-of-a-column-in-eloquent model ```php use Illuminate\Database\Eloquent\Model; class SomeModel extends Model { public function getTagNameAttribute() { return $this->attributes['some_column_name']; } } ``` ---