Friday 15 February 2019

Laravel eloquent useful notes

LARAVEL how to get inserted id:
after $data->save(); the newly inserted auto id, can be retrieved using $data->id


Laravel where queries Elqouent:
In Laravel 5.3 you can use more granular wheres passed as array:
$query->where([
    ['column_1', '=', 'value_1'],
    ['column_2', '<>', 'value_2'],
    [COLUMN, OPERATOR, VALUE],
    ...
])
Personally I haven't found use-case for this over just multiple where calls, but fact is you can use it.
Since June 2014 you can pass an array to where
As long as you want all the wheres use and operator, you can group them this way:
$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];

// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' => 'yet_another_value', ...];
Then:
$results = User::where($matchThese)->get();

// with another group
$results = User::where($matchThese)
    ->orWhere($orThose)
    ->get();
The above will result in such query:
SELECT * FROM users
  WHERE (field = value AND another_field = another_value AND ...)
  OR (yet_another_field = yet_another_value AND ...)

Laravel elqouent 
 $table->timestamps();
will create created_at, updated_at column, 
to not use that remove this line, and add your own created_at, updated_at column

No comments:

Post a Comment