Laravel Snippets

Laravel Snippets

Multi File upload (Only Square Images)

<!-- HTML Form -->
<input type="file" name="images[]" accept="image/*" multiple>
// Form Request Class
public function rules()
{
    return [
        // dimensions:ratio=1/1 = Square, remove/change if neccessory
        'images.*' => 'bail|required|image|mimes:jpeg|dimensions:ratio=1/1',

        // Max 5 file uploads is allowed at once.
        'images' => 'max:5',
    ];
}

// Customized error messages
public function messages()
{
    return [
        'images.max' => 'Maximum 5 images are allowed at once.',
        'images.*.mimes' => 'Only jpeg images are allowed.',
        'images.*.dimensions' => 'Only square images are allowed.'
    ];
}
// Controller, May need many changes
foreach ($request->images as $photo) {
    $path = $photo->storeAs('products', md5_file($photo) . '.jpg', 'public');
    try {
        $product->photo()->save(new Photo([
            'path' => $path,
        ]));
    } catch (Exception $exception) {
        continue;
    }
}
// Validation Rules
public function rules()
{
  return [
      'link' => 'required|unique:product_videos,link',
  ];
}

// Extract ID from URL
protected function prepareForValidation()
{
  $this->merge([
      'link' => $this->extractYouTubeVideoId($this->link),
  ]);
}

// Custom Validation Messages
public function messages()
{
    return [
        'link.required' => 'Invalid link'
    ];
}

// Extract ID from URL
private function extractYouTubeVideoId($link)
{
    try {
        // For videos like http://www.youtube.com/watch?v=...
        $video_id = explode("?v=", $link);

        // For videos like http://www.youtube.com/watch/v/..
        if (empty($video_id[1])) {
            $video_id = explode("/v/", $link);
        }

        // Deleting any other params
        $video_id = explode("&", $video_id[1]);
        $video_id = $video_id[0];
        return $video_id;
    } catch (\Exception $exception) {
        return null;
    }
}

CSV to Array

<input class="form-control" name="value" type="text" required>
public function rules()
{
    return [
        'tags' => 'required|array',
    ];
}

protected function prepareForValidation()
{
    $this->merge([
        'tags' => array_map('ucfirst', array_map('trim', explode(',', $this->value))),
    ]);
}
// Controller
foreach ($request->tags as $value) {
    try {
        $product->attribute()->save(new ProductAttribute([
            'name' => $request->name,
            'value' => $value,
            'price' => $request->price,
        ]));
    } catch (Exception $exception) {
        continue;
    }
}

Bootstrap Form Boilerplate

<div class="form-group row">
    <label for="email" class="col-sm-4 col-form-label text-md-right">E-Mail Address</label>

    <div class="col-md-6">
        <input id="email" type="email" name="email" required autofocus
        class="form-control{{ $errors->has('email')? ' is-invalid':'' }}"
        value="{{ old('email') }}">

        @if ($errors->has('email'))
            <span class="invalid-feedback" role="alert">
                <strong>{{ $errors->first('email') }}</strong>
            </span>
        @endif
    </div>
</div>

Form Request Boilerplate


use Illuminate\Validation\Rule;

public function rules()
{
    return [
        'type' => ['required', Rule::in(['Home', 'Office'])],
        'line1' => 'required|string|max:256',
        'line2' => 'required|string|max:256',
        'landmark' => 'nullable|string|max:128',
        'city' => 'required|string|max:64',
        'state' => 'required|string|max:64',
        'pin' => 'required|digits:6|max:64'
    ];
}

Controller Boilerplate


public function __construct()
{
    $this->middleware('active');
}

public function index()
{
    $addresses = auth()->user()->address;
    return view('address.index', compact('addresses'));
}

public function create()
{
    return view('address.create');
}

public function store(AddressRequest $request)
{
    auth()->user()->address()->save(new Address($request->validated()));
    return redirect('/address')->with('message', 'Address Added Successfully');
}

public function show(Address $address)
{
    abort(403);
}

public function edit(Address $address)
{
    if (auth()->id() === $address->user_id) {
        return view('address.edit', compact('address'));
    }
}

public function update(AddressRequest $request, Address $address)
{
    if (auth()->id() === $address->user_id) {
        $address->update($request->validated());
        return redirect('/address')->with('message', 'Address Updated Successfully');
    }
}

public function destroy(Address $address)
{
    if (count(auth()->user()->address) <= 1) {
        return redirect('/address')->with('error', 'At least one address is required');
    }

    if (auth()->id() === $address->user_id) {
        $address->delete();
        return redirect('/address')->with('message', 'Address Deleted Successfully');
    }
}

Validation Boilerplate


// Strings
'string' => 'required|string|max:256',
'boolean' => 'required|boolean',

// 10 Digit mobile number
'mobile' => 'required|digits:10|unique:users',

// Input should be Home or Office
'inThis' => ['required', Rule::in(['Home', 'Office'])],

// Should exists in categories table in id column
'parent' => 'integer|exists:categories,id',

// Should be an array, used with CSV input, check perpareForValidation for more info.
'value' => 'required|array',

// Multifile upload
'images.*' => 'required|image|mimes:jpeg|dimensions:ratio=1/1',

// Multifile upload limit
'images' => 'max:5',

Error File Boilerplate

@if ($flash = session('message'))
    <li class="list-group-item list-group-item-success" role="alert">{{ $flash }}</li>
@endif

@if ($flash = session('error'))
    <li class="list-group-item list-group-item-danger" role="alert">{{ $flash }}</li>
@endif

@if ($errors->any())
    <ul class="list-group">
        @foreach ($errors->all() as $err)
            <li class="list-group-item list-group-item-danger" role="alert">{{ $err}}</li>
        @endforeach
    </ul>
@endif

Bootstrap Boilerplate

<!-- layouts.master -->
<!DOCTYPE html>
<html lang="en_US">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="@csrf">
    <title>@yield('title') - {{ config('app.name', 'Laravel') }}</title>
    @include('layouts.stylesheets')
    @yield('style')
</head>
<body>
    @yield('content')
    @include('layouts.scripts')
    @yield('script')
</body>
</html>
<!-- stylesheets.blade.php -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- scripts.blade.php -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="{{ asset('js/app.js') }}"></script>

Midlleware Boilerplate

public function handle($request, Closure $next)
{
    if (!$request->user()->isAdmin()) {
        abort(403);
    }

    return $next($request);
}

Open Graph Boilerplate

Working on it.


Original:  Updated: