PHP code example of osoobe / laravel-utilities

1. Go to this page and download the library: Download osoobe/laravel-utilities library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

osoobe / laravel-utilities example snippets


Schema::create('businesses', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->location();         // country, state, city, street_address, zip_code
    $table->addLocationIndex(); // adds individual indexes on each location column
    $table->timestamps();
});

// Rolling back
Schema::table('businesses', function (Blueprint $table) {
    $table->dropLocationIndex();
    $table->dropLocation();
});

Schema::create('properties', function (Blueprint $table) {
    $table->id();
    $table->coordinates(); // latitude (decimal 16,13), longitude (decimal 16,13)
    $table->timestamps();
});

Schema::table('properties', function (Blueprint $table) {
    $table->dropCoordinates();
});

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->userstamp(); // creator_id, creator_type, editor_id, editor_type
    $table->timestamps();
});

Schema::table('posts', function (Blueprint $table) {
    $table->dropUserstamp();
});

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->isActive(); // is_active tinyint, nullable, default 1
    $table->timestamps();
});

use Osoobe\Utilities\Traits\Active;

class Product extends Model
{
    use Active;
}

// Usage
Product::active()->get();       // WHERE is_active = 1
Product::notActive()->get();    // WHERE is_active != 1
Product::hidden()->get();       // WHERE hidden = 1

use Osoobe\Utilities\Traits\HasVerified;

class Listing extends Model
{
    use HasVerified;
}

Listing::verified()->get();
Listing::notVerified()->get();

use Osoobe\Utilities\Traits\IsDefault;

class PaymentMethod extends Model
{
    use IsDefault;
}

PaymentMethod::isDefault()->first();
PaymentMethod::notDefault()->get();

use Osoobe\Utilities\Traits\Sorted;

class MenuItem extends Model
{
    use Sorted;
}

MenuItem::sorted()->get(); // ORDER BY sort_order ASC

use Osoobe\Utilities\Traits\HasSlug;

class Article extends Model
{
    use HasSlug;
}

// Finds by slug OR id — useful for route model binding
$article = Article::findBySlugOrFail('my-article-title');

use Osoobe\Utilities\Traits\HasEmail;

class User extends Model
{
    use HasEmail;
}

User::emailVerified()->get();
User::emailNotVerified()->get();
User::email('[email protected]')->first();

// Users who verified their email within the last 7 days
User::emailVerifiedSince(7)->get();

// Check on an instance
if ($user->isEmailVerified()) { ... }

use Osoobe\Utilities\Traits\Userstamp;

class Invoice extends Model
{
    use Userstamp;
}

// No manual work needed — creator and editor are set automatically on save.
$invoice = Invoice::create(['amount' => 500]);
echo $invoice->creator_type; // "App\Models\User"
echo $invoice->creator_id;   // 42

use Osoobe\Utilities\Traits\TimeDiff;

class JobPost extends Model
{
    use TimeDiff;
}

// Scopes
JobPost::createdToday()->get();
JobPost::createdSinceWeek()->get();
JobPost::recentlyCreated(3)->get();         // last 3 days
JobPost::recentlyCreated(2, 'subWeeks')->get(); // last 2 weeks
JobPost::betweenDates('created_at', $start, $end)->get();
JobPost::expired()->get();
JobPost::notExpired()->get();

// Accessor
echo $post->created_time_diff; // "3 days ago"

// Instance methods
$post->expireInDays(30);
$post->expireInHours(48);
if ($post->isExpired()) { ... }
if ($post->recentlyCreated(1)) { ... }

// In migration
use Osoobe\Utilities\Helpers\MigrationHelper;

public function up()
{
    MigrationHelper::addFullTextSearch('articles', ['title', 'body'], 'articles_search');
}

use Osoobe\Utilities\Traits\FullTextSearchTrait;

class Article extends Model
{
    use FullTextSearchTrait;
}

// Natural language search
Article::fullTextSearch(['title', 'body'], 'laravel utilities')->get();

// Boolean mode
Article::fullTextSearch(['title', 'body'], '+laravel -utilities', true)->get();

// OR version (FullTextSearchTrait only)
Article::orFullTextSearch(['title', 'body'], 'alternative terms')->get();

// Include relevance score in SELECT
$score = Article::selectFTSScore(['title', 'body'], 'laravel');
Article::selectRaw($score)->orderByDesc('fts_score')->get();

use Osoobe\Utilities\Traits\AdvanceWhereQuery;

class Order extends Model
{
    use AdvanceWhereQuery;
}

// Applies the WHERE only when $value is non-empty; skips it otherwise
Order::whereKeyOrNull('status', $request->status)->get();

use Osoobe\Utilities\Traits\ModelDefaultTrait;

class Subscription extends Model
{
    use ModelDefaultTrait;

    public function defaultModelValues(): void
    {
        $this->status = $this->status ?? 'trial';
        $this->trial_ends_at = $this->trial_ends_at ?? now()->addDays(14);
    }
}

use Osoobe\Utilities\Traits\SEO;

class Product extends Model
{
    use SEO;

    public function getRouteURL(): string
    {
        return route('products.show', $this->slug);
    }

    public function getSEOTitleAttribute(): string
    {
        return $this->name . ' | My Shop';
    }

    public function getSEODescriptionAttribute(): string
    {
        return $this->summary;
    }
}

// $product->url returns getRouteURL()
// $product->seo_title and $product->seo_description are accessible as attributes

use Osoobe\Utilities\Traits\Lang;

class Post extends Model
{
    use Lang;
}

Post::lang()->get();   // WHERE lang = current locale
Post::langEN()->get(); // WHERE lang = 'en'

use Osoobe\Utilities\Helpers\Utilities;

// Safe object/array access
$name = Utilities::getObjectValue($user, 'name', 'Guest');
$name = Utilities::getObjectValue($user, ['display_name', 'name'], 'Guest'); // tries each key
$val  = Utilities::getArrayValue($data, 'key', 'default');

// Only set if the value is non-empty
Utilities::setObjectValue($model, 'bio', $request->bio);
Utilities::setArrayValue($data, 'phone', $request->phone);
Utilities::setArrayValueIfEmpty($settings, 'theme', 'light');

// Math
Utilities::calcNumberPercentage(15, 200); // 15% of 200 = 30
Utilities::calc_percentage(30, 200);      // 30/200 as percentage = 15
Utilities::calcAverage(10.0, 20.0, 30.0); // 20.0
Utilities::calcAverageNoZeros(0, 10.0, 20.0); // ignores zeros

// Phone
Utilities::formatPhoneNumber('5551234567');   // "+15551234567"
Utilities::formatPhoneNumber('+15551234567'); // "+15551234567"

// Compare two Eloquent models
Utilities::model_compare($userA, $userB); // true if same class and id

// Email variation regex (handles dots and + aliases)
$regex = Utilities::getEmailVariationRegex('[email protected]');

// Array helpers
Utilities::isAssociativeArray(['a' => 1]); // true
Utilities::toAssociativeArray(['a', 'b']); // ['a' => 'a', 'b' => 'b']
Utilities::removeEmpty([0, '', null, 'hello']); // [0, 'hello']

// CSV
$rows = Utilities::csvToArray('/path/to/file.csv');
Utilities::outputCSV('/path/to/output.csv', $rows);

use Osoobe\Utilities\Helpers\Str;

Str::ucwords('hello world');       // "Hello World"
Str::ucsnake('helloWorld');        // "Hello_World"
Str::boolToString(true);           // "Yes"
Str::boolToString(false, 'B');     // "False"

$parts = Str::nameParts('John Michael Doe');
// $parts->first_name  = "John"
// $parts->middle_name = "Michael"
// $parts->last_name   = "Doe"

use Osoobe\Utilities\Helpers\FormatHelper;

// Auto-detects type
FormatHelper::formatString('https://example.com', 'html');
// <a class='lm-format' href='https://example.com'>https://example.com</a>

FormatHelper::formatString('[email protected]', 'markdown', 'Contact');
// [Contact](mailto:[email protected])

FormatHelper::formatPhone('+15551234567', 'html', 'Call Us');
// <a class='lm-format' href='tel:+15551234567'>Call Us</a>

FormatHelper::formatEmail('[email protected]', 'markdown');
// [[email protected]](mailto:[email protected])

use Osoobe\Utilities\Helpers\Date;

$period = Date::getStartEndDate(Carbon::now(), 'weekly');
// $period->start_date  (start of week)
// $period->end_date    (end of week)
// $period->date        (the input date)

// Supported periods: 'daily'/'day', 'weekly'/'week', 'monthly'/'month'

Date::isBetweenPeriod(Carbon::now(), 'monthly'); // true if today is within the current month

use Osoobe\Utilities\Helpers\MigrationHelper;

// Add a MySQL FULLTEXT index
MigrationHelper::addFullTextSearch('products', ['name', 'description'], 'products_search');

use Osoobe\Utilities\Helpers\PhoneNumberHelper;

PhoneNumberHelper::isValid('+1 (555) 123-4567'); // true
PhoneNumberHelper::isValid('123');               // false (too short)

use Osoobe\Utilities\Helpers\ImageHelper;

// Store a base64 image from an API request or form upload
$path = ImageHelper::storeBase64Image(
    $request->avatar,       // data:image/png;base64,...
    'avatars',              // directory
    'user-42',              // filename (extension auto-detected)
    'public',               // filesystem disk
    'public'                // visibility
);
// Returns the stored path, e.g. "avatars/user-42.png", or false on failure

// Strip the data URI prefix
$raw = ImageHelper::base64Only('data:image/jpeg;base64,/9j/4AAQ...');

use Osoobe\Utilities\Helpers\MapBoxHelper;

$data = MapBoxHelper::queryLocationData(config('services.mapbox.key'), '1600 Pennsylvania Ave NW, Washington DC');
$cords = MapBoxHelper::getCordsFromData($data);
// $cords->latitude, $cords->longitude

$address = MapBoxHelper::getAddressComponent($data);
// $address->street_address, ->city, ->state, ->state_short,
// ->country, ->country_short, ->zip_code, ->latitude, ->longitude, ->full_address

// Reverse geocode
$data = MapBoxHelper::queryCoordinates(config('services.mapbox.key'), 38.8977, -77.0365);

use Osoobe\Utilities\Helpers\GoogleMapsHelper;

$cords = GoogleMapsHelper::getGoogleMapCordinates(
    config('services.google.maps_key'),
    '1600 Pennsylvania Ave NW Washington DC'
);
// ['latitude' => 38.897..., 'longitude' => -77.036...]

return [
    'users' => [
        'model'            => \App\Models\User::class,
        'id_column'        => 'id',
        'text_column'      => 'name',
        'full_text_search' => ['name', 'email'],
        '' => [
        'model'       => \App\Models\Category::class,
        'id_column'   => 'id',
        'text_column' => 'name',
        '

$request->validate([
    'mobile' => '

'phone' => [
    'pattern' => '%^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$%i',
],

$request->validate([
    'password' => '

'password' => [
    'pattern' => '^(?=.*[A-Z])(?=.*\d).{8,}$',
    'message' => 'The :attribute must contain at least one uppercase letter and one number.',
],

use Osoobe\Utilities\Console\Command;

class SyncInventory extends Command
{
    protected $timer = true; // prints "Took 2 minutes to complete" after handle()
    protected $signature = 'inventory:sync';

    public function handle()
    {
        // long-running work
    }
}

class Contact extends Model
{
    use Userstamp, Active;
}

// In migration
$table->userstamp();
$table->isActive();

// Query active contacts created by a specific user
Contact::active()->where('creator_id', auth()->id())->get();

class JobPost extends Model
{
    use TimeDiff, FullTextSearchTrait;
}

// Active, non-expired listings matching a keyword, sorted by relevance
$score = JobPost::selectFTSScore(['title', 'description'], $keyword);
JobPost::notExpired()
    ->selectRaw("*, $score")
    ->fullTextSearch(['title', 'description'], $keyword)
    ->orderByDesc('fts_score')
    ->get();

class Property extends Model
{
    use ModelDefaultTrait;

    public function defaultModelValues(): void
    {
        if ($this->street_address && !$this->latitude) {
            $data = MapBoxHelper::queryLocationData(
                config('services.mapbox.key'),
                $this->street_address . ', ' . $this->city
            );
            $cords = MapBoxHelper::getCordsFromData($data);
            if ($cords) {
                $this->latitude  = $cords->latitude;
                $this->longitude = $cords->longitude;
            }
        }
    }
}

// config/api-endpoints.php
'products' => [
    'model'            => \App\Models\Product::class,
    'id_column'        => 'id',
    'text_column'      => 'name',
    'full_text_search' => ['name', 'sku', 'description'],
    '

public function updateAvatar(Request $request)
{
    $path = ImageHelper::storeBase64Image(
        $request->input('avatar'),
        'avatars/' . auth()->id(),
        'profile',
        'public',
        'public'
    );
    if ($path) {
        auth()->user()->update(['avatar_path' => $path]);
    }
}

class Product extends Model
{
    use SEO, HasSlug;

    public function getRouteURL(): string
    {
        return route('products.show', $this->slug);
    }

    public function getSEOTitleAttribute(): string
    {
        return $this->name . ' — ' . config('app.name');
    }

    public function getSEODescriptionAttribute(): string
    {
        return Str::limit($this->description, 155);
    }
}
bash
php artisan vendor:publish --provider="Osoobe\Utilities\UtilitiesServiceProvider"