Skip to content

Instantly share code, notes, and snippets.

@ManojKiranA
Forked from ctf0/-laravel tips.md
Created August 26, 2019 12:25
Show Gist options
  • Save ManojKiranA/10154bcf6615b7632686fe9847ac8c2b to your computer and use it in GitHub Desktop.
Save ManojKiranA/10154bcf6615b7632686fe9847ac8c2b to your computer and use it in GitHub Desktop.
laravel tips
<?php
namespace App\Traits;
use Carbon\Carbon;
use Jenssegers\Date\Date;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
trait HasTranslatedDates
{
/*
* Return a timestamp as DateTime object.
* over-ride the original.
* \vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php.
*
* @param mixed $value
*
* @return \Illuminate\Support\Carbon
*/
protected function asDateTime($value)
{
// Carbon::setLocale(LaravelLocalization::getCurrentLocale()); // just in case
Date::setLocale(LaravelLocalization::getCurrentLocale());
return new Date(parent::asDateTime($value));
}
}
  • 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;
    },
]);

filter relation data

  • loose
$logs = Advertisment::with(['advertiser', 'carGroup', 'targets', 'advertismentlogs']);
$logs->whereHas('targets', function ($query) use ($targets) {
    $query->where('name', $targets[0]);
    array_shift($targets);

    foreach ($targets as $name) {
        $query->orWhere('name', $name);
    }
});
  • restrict
$logs = Advertisment::with(['advertiser', 'carGroup', 'targets', 'advertismentlogs']);
foreach ($targets as $name) {
    $logs->whereHas('targets', function ($query) use ($name) {
        $query->orWhere('name', $name);
    });
}

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 class="form-text invalid-feedback d-block">{{ $one }}</small>
            <br>
        @endforeach
    @else
        <small class="form-text invalid-feedback d-block">{{ $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 hydarte checkbox
/**
 * auto hydrate checkboxs false value.
 *
 * http://novate.co.uk/laravel-5-checkbox-processing/
 * https://medium.com/@secmuhammed/laravel-observers-e68c69a8c8c6
 *
 * @param Illuminate\Database\Eloquent\Model $model   [$model description]
 * @param Illuminate\Http\Request            $request [$request description]
 *
 * @return [type] [return description]
 */
protected function hydrateCheckboxs(Model $model, Request $request)
{
    $model = app($model);

    if (property_exists($model, 'casts')) {
        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;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment