Skip to content

Instantly share code, notes, and snippets.

@ctf0
Last active October 21, 2023 05:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ctf0/b6b0f660856398c9385ba74147cb3fe4 to your computer and use it in GitHub Desktop.
Save ctf0/b6b0f660856398c9385ba74147cb3fe4 to your computer and use it in GitHub Desktop.
laravel tips
  • php assoc array to correct js array of objs
$data = [
    'Users' => 'abc',
    'posts' => 'blabla',
];

collect($data)->map(function ($v, $k) {
    return [
        'name'=> $k,
        'data'=> $v,
    ];
})->values();


  • check for something in db while validating
$this->validate($request, [
    'attr'=> function ($attribute, $value, $fail) use ($id) {
        return DB::table('table-name')
            ->where('attr', 'some-value')
            ->where('id', '!=', $id) // unique check on update
            ->first()
        ? $fail('there is already another item with the same value')
        : true;
    },
]);

to make sure tha querystring is always used with the pagination use ->appends(request()->query())

$items
    ->paginate(3)
    ->appends(request()->query()),


fire update event on mass update

$items->update([
    // ...
    'updated_at'=>now()
]);

make sure only one attribute was changed

  • inside the updated model event u can use something like
if ($model->wasChanged('attribute_name') && count($model->getDirty()) == 1) {
    // do stuff
}

to get model instance class name

// it self
class_basename(Model::first());

// relation
class_basename(model->relationName()->getRelated());

for filtration

  • to filter model it self where
  • to filter model based on relation whereHas('relation', function($q) {...})
  • to filter model relation with('relation', function($q){...})

pluck nested

Collection::macro('pluckMulti', function ($field) {
    $arr = explode('.', $field);
    $toGet = array_pop($arr);

    $res = $this;
    foreach ($arr as $relation) {
        $res = $res->pluck($relation)->flatten();
    }

    return $res->pluck($toGet);
});

display validation errors for single & array

@foreach ($errors->get($input) as $item)
    @if (is_array($item))
        @foreach ($item as $one)
            <small>{{ $one }}</small>
            <br>
        @endforeach
    @else
        <small>{{ $item }}</small>
    @endif
@endforeach

model automation inside observers

note that you cant do any correct checkes inside any of the observer methods because laravel doesnt return the whole model, instead it only return the changed/inserted data,

so to solve this you will need to use $model = $model->fresh() which will create a new db query in order to get you the full data,

otherwise your checks wont work because it will be doing it against the old data not the newly changed/inserted .


auto hydrate checkbox

/**
 * auto hydrate checkboxes false value.
 *
 * http://novate.co.uk/laravel-5-checkbox-processing/
 * https://medium.com/@secmuhammed/laravel-observers-e68c69a8c8c6
 *
 * when using `request()->all()` add it under the controller method
 * when using `request()->validated()` add it under the form-request `validationData()`
 *
 * @param [type] $model   [$model description]
 * @param [type] $request [$request description]
 *
 * @return [type] [return description]
 */
public function hydrateCheckboxes($model, $request)
{
    $model = app($model);

    collect($model->getCasts())
        ->filter(function ($v, $k) {
            return $v == 'boolean';
        })->each(function ($v, $k) use ($request) {
            $request->merge([$k => $request->input($k, false)]);
        });

    return $request;
}

and use it like so $this->hydrateCheckboxes(ModelName::class, $request);


use relation with any column

  • for example you want to get the similar records based on a column ex.price
public function similar() {
    $col = 'price';

    return $this->hasMany(self::class, $col, $col);
}

and now use it like

// get main model along with all other records that have the same exact price or whatever column u chose
Model::with('similar', function($q) {
    $q->whereNotIn('id', [$id]) // exclude self
})->find($id)->similar;

// or
Model::find($id)
    ->similar()
    ->whereNotIn('id', [$id]) // exclude self
    ->get();

// or
Model::with('similar')
    ->find($id)
    ->similar
    ->exclude($id); // exclude self


// https://stackoverflow.com/a/43721733/3574919
$query->toSql();
$query->getBindings()

yes | php artisan migrate


  • localization for carbon
// AppServiceProvider
public function boot()
{
    Carbon::setLocale(app()->getLocale());
}

// now use it like
$model->created_at->translatedFormat('D Y-m-d, g:i A')

  • to simplify observer registration, u can use
$list = [
    'ModelName',
];

foreach ($list as $model) {
    app("App\\$model")->observe(app("App\\Observers\\{$model}Observer"));
}

just make sure the observer name is starting with the model name ex.UserObserver


  • carbon diffInDays might not work as expected especially when using unix comparison, as both have to match in time "hr, min, etc..." to get correct days diff, so to get around that, we can use floatDiffInDays
$tz = config('app.timezone');
$start = \Carbon(1606389724, $tz);
$end = \Carbon(1606735320, $tz);

$days = round($start->floatDiffInDays($end));

  • when working with policies, unless u r using authorizeResource, u'll need to add the authorize check ur self ex.
public function __construct()
{
    // update == policy method name
    // post == the model policy we are targeting
    $this->middleware('can:update,post')->only('update');
}

// or
public function update(Request $request, Post $post)
{
    $this->authorize('update', $post);

    // or even simpler
    // * just make sure the `policy method` == `controller method` aka `update`
    $this->authorize(__FUNCTION__, $post);
}

  • to query something where date has passed "5 mins from the start"
$q->where('from_date', '<=', now()->subMinutes(5));
  • to query something where date has remaining "5 mins to the end"
$q->where('to_date', '>=', now()->addMinutes(5));

postman & laravel

Make sure to set the `X-Requested-With` to `XMLHttpRequest` when working with Postman. Otherwise, Laravel won't recognize the call as an AJAX request.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment