Eloquent ORM

It is object relational mapper that provides smooth interaction with database.
 

Using selectRaw with aggregate function, where, orderBy, groupBy, take and get

UserPoint::selectRaw("TRUNCATE(SUM(amount),2) as summ, COUNT(id) as cnt") ->where('archive', 0) ->orderBy("dat",desc) ->groupBy("dat") ->take(13) ->get()


Using WhereIn

$whereTypes = ['png','jpeg','JPG','jpg']; $media = PostFile::where('post_id', $post->id)->whereIn('type', $whereTypes)->first();


Updating multiple rows

$values = Value::where('project_id', $id)->update(['data'=>$data]);


How to delete all the rows in a table

\App\Model::query()->delete();


How to use count with where condition

$active_requests = UserPiggyBank::where('process',1)->count();


How to get names in list instead of associated array ( id as key and name as value )

PiggyBankCategory::orderBy( 'name', 'asc' )->get()->pluck('name', 'id');


Using Like

BookingDates::where('email', Input::get('email')) ->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();


Checking what query is run with eloquent

If you want to see what is run in the database use dd(DB::getQueryLog()) to see what queries were run.


Using orWhere

$query->where( 'id', $request->query( 'keyword' ) )->orWhere('company_name', $keyword)->orWhere('job_number', $keyword);


How to use condition in query dynamically

$query = Order::query(); $keyword = $request->query( 'keyword' ) ?? ''; if ( !empty( $request->query( 'keyword' ) ) ) { $query->where(...