PHP code example of slruslan / laravel-eloquent-custom-casts

1. Go to this page and download the library: Download slruslan/laravel-eloquent-custom-casts 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/ */

    

slruslan / laravel-eloquent-custom-casts example snippets


namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Slruslan\CustomCasts\CustomCasts;

class Post extends Model
{
    use CustomCasts;


    protected $casts = [
        'geo_location' => \App\Services\CustomLocation::class,
        'another_custom_field' => \App\Services\AnotherCustomField::class
    ];

    $post = Post::find(1);

    // For example, imagine we have an \App\Services\CustomLocation class,
    // that implements any custom logics and for some reasons
    // we have to store it in DB as it is.

    // Let's instantinate it.
    $location = new \App\Services\CustomLocation(55.9937441, 92.7521816);

    // And call some methods, imagine we have them there.
    $location->updatePosition();
    $location->callAPI();

    // After that, we want to save it in our post model.
    // We can just assign the value and call default save() method.
    $post->geo_location = $location;
    $post->save();

    // It's saved. Let's get a post again
    // and check the field class.

    $post = Post::find(1);

    var_dump($post instanceof \App\Services\CustomLocation);

    // Outputs:
    // bool(true)