Joshua Carter

Joshua Carter

1586950440

Accessors and Murators in Laravel 7.x

Introduce

Accessors and Murators allow you to format Eloquent properties when we retrieve or add new models. For example, when adding a user you want before adding, it automatically encrypts the value of the password before being saved to the database or retrieving a name from the database as a print. flowers then accessorsand muratorswill help us to do this. In addition, Eloquent can also automatically convert the date field into a Carbon instance or convert a text into a json data type.

1. Define an Accessors

A little briefly accessorswill help us format the data when we get data from the database. Suppose we have a field namein a table userand want it to be capitalized when retrieving data. First we need to create a method to define this in the model Useras getfield name in uppercase lettersAttribute. In this case the method written will be getNameAttribute.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{

    public function getNameAttribute($value)
    {
        return strtoupper($value);
    }
}

Now try to see how the result looks like, you will create one routeas follows:

Route::get('/accessors', function() {
  $user = App\User::find(1);

  return $user->name;
});

Now go to localhost: 8000 / accessors and see the results.

Or you can even define a new property with existing attributes, for example:

public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

The procedure is similar

$user->fullname;

2. Defining a murators.

Other than that, accessorsit is muratorsused to format data before saving it into a database. To define a muratorssimilarity with accessorsjust another is the prefix would be set. For example, we will format the field nameto non-capitalized before saving it to the database. So the method here will besetNameAttribute

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = strtolower($value);
    }
}

To test we also create a route with the following content:

Route::get('/murators', function() {
  $user = App\User::find(1);
  $user->name = "CCC";
  $user->save();
  return $user->name;
});

To check the data saved correctly or not to open php artisan tinkerup to the test App\User::find(1), we will see the value of the namemedium will be saved ccc.

3. Date Murators

By default, Eloquent will automatically convert two fields created_atand update_atinto a Carbon instance, and it provides a lot of useful functions. We can also add date attributes using the $datemodel

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'seen_at',
    ];
}

When a field is of type dateyou can set its value as a UNIX timestamp, date string (Ymd), date-time string or an instance of Carbon, and the value of the date will automatically be stored in the database.

Date formats

By default the timestamps are formatted Y-m-d H:i:s, you can customize this format by using the attribute dateFormatin the model, which will reformat as the date data type to be stored in the database.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $dateFormat = 'Y-m-d';
}

4. Attribute Casting

Attributes $casthelp convert attributes to normal data types. The property $castis usually an array with the key being the name of the property to be transferred and value being the type of data you want to convert. The type of data that the attribute $castsupports: integer, real, float, double, decimal:<digits>, string, boolean, object, array, collection, date, datetime, and timestamp. For example, we have the attribute is_adminstored in the database is 0and 1with the data type integerbut you want to use it as the data type boolean, do the following

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

We then use it is_adminas a property of data typeboolean

$user = App\User::find(1);

if ($user->is_admin) {

}

Custom cast

You can define an attribute castfor your own by creating an implements class from the CastsAttributesinterface. One thing to note is that this newly created class must exist two methods getand setwith different tasks. The method is getused to convert data in the database to the data type castyou define, and the method sethas the opposite task to convert the converted data into the original data type to store in the database. For example, we custom attribute castis json data type.

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Json implements CastsAttributes
{

    public function get($model, $key, $value, $attributes)
    {
        return json_decode($value, true);
    }

    public function set($model, $key, $value, $attributes)
    {
        return json_encode($value);
    }
}

Then we will use it in the model.

<?php

namespace App;

use App\Casts\Json;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    protected $casts = [
        'options' => Json::class,
    ];
}

Array & JSON Casting

Cast The array type is useful when we use them with columns stored as json.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    protected $casts = [
        'options' => 'array',
    ];
}

When declared like this, we will use and process the data as an array in PHP. When you set a value for a property options, the given array is automatically converted back into JSON for storage:

$user = App\User::find(1);

$options = $user->options;

$options['key'] = 'value';

$user->options = $options;

$user->save();

Date Casting

When used castwith date and datetime data types, we can reformat for this data type

protected $casts = [
    'created_at' => 'datetime:Y-m-d',
];

Query Time Casting

Sometimes you can use both castin queries

use App\Post;
use App\User;

$users = User::select([
    'users.*',
    'last_posted_at' => Post::selectRaw('MAX(created_at)')
            ->whereColumn('user_id', 'users.id')
])->get();

The property is last_posted_atbased on the result of the selectRaw statement, which makes sense if we set the data type to last_posted_ata date type, simply by using the method withCasts.

$users = User::select([
    'users.*',
    'last_posted_at' => Post::selectRaw('MAX(created_at)')
            ->whereColumn('user_id', 'users.id')
])->withCasts([
    'last_posted_at' => 'date'
])->get();

You can also see how other useful properties this castbrings here .

#php #laravel

What is GEEK

Buddha Community

Accessors and Murators in Laravel 7.x

How to Send E-mail Using Queue in Laravel 7/8

Today I will show you How to Send E-mail Using Queue in Laravel 7/8, many time we can see some process take more time to load like payment gateway, email send, etc. Whenever you are sending email for verification then it load time to send mail because it is services. If you don’t want to wait to user for send email or other process on loading server side process then you can use queue.

Read More : How to Send E-mail Using Queue in Laravel 7/8

https://websolutionstuff.com/post/how-to-send-e-mail-using-queue-in-laravel-7-8


Read Also : Send Mail Example In Laravel 8

https://websolutionstuff.com/post/send-mail-example-in-laravel-8

#how to send e-mail using queue in laravel 7/8 #email #laravel #send mail using queue in laravel 7 #laravel 7/8 send mail using queue #laravel 7/8 mail queue example

I am Developer

1597817005

Bar Code Generator In Laravel 7.x

Bar Code Generate in Laravel 7, 6. In this post, i will show you simple and easy steps to generate bar/qr code in laravel.

Generate Bar codes in Laravel

Use the below given steps and generate bAR/QR codes in laravel Projects:

  1. Install Laravel Fresh Setup
  2. Set database Credentials In .env File
  3. Install simple-QRcode Package
  4. Register Package
  5. Test Qr Code
  6. Conclusion

https://www.tutsmake.com/laravel-6-simple-generate-or-create-qr-codes-example/

#laravel 7 bar code generator #barcode generator laravel 7 #barcode generator laravel 6 #laravel 7 qr code generator #laravel simple/barcode example

Laravel Accessor and Mutator Example

In this post we will see laravel accessor and mutator example, here we will see what is accessor and mutator, how to use accessor and mutator with example.

laravel mutator is used to set attribute, laravel accessor is used to get attribute in laravel , below i have added more information of Accessor and mutator with example

Read More : Laravel Accessor and Mutator Example

https://websolutionstuff.com/post/laravel-accessor-and-mutator-example


You May Also Like :

  1. https://websolutionstuff.com/post/jquery-image-magnifier-on-mouse-hover
  2. https://websolutionstuff.com/post/laravel-8-socialite-login-with-google-account
  3. https://websolutionstuff.com/post/laravel-8-form-class-not-found

#laravel accessor and mutator example #laravel accessor #mutator #php laravel #laravel 8 #laravel

I am Developer

1597727551

Laravel 7 Crud using Datatables

yajra datatables crud with ajax in laravel 7. In this post, i will show you how to create crud using datatable in laravel with ajax and model.

Now, i am going to show you how to install and use datatables in laravel 7 application. i will use jquery ajax crud with modals using datatables js in laravel 7. i will write easy code of jquery ajax request for crud with yajra datatable.

Laravel 7 DataTable CRUD Example

Use the below steps and create yajra DataTables crud with ajax in laravel:

Step 1: Install Laravel App For DataTable Crud
Step 2: Configuration .evn file
Step 3: Run Migration
Step 4: Install Yajra DataTables Package
Step 5: Add Fake Data into Database table
Step 6: Add Datatable Ajax Route
Stpe 7: Create DataTableController
Step 8: Create Ajax Datatable Blade View
Step 9: Start Development Server

https://www.tutsmake.com/laravel-7-6-install-yajra-datatables-example-tutorial/

#laravel 6 yajra datatables #yajra datatables laravel 6 example #laravel-datatables crud #yajra datatables laravel 7 #laravel 7 datatables #yajra datatables laravel

I am Developer

1597563325

Laravel 7/6 Image Upload Example Tutorial

Laravel image upload example tutorial. Here, i will show you how to upload image in laravel 7/6 with preview and validation.

Before store image into db and folder, you can validate uploaded image by using laravel validation rules. as well as you can show preview of uploaded image in laravel.

Image Upload In Laravel 7/6 with Validation

Image upload in laravel 7/6 with preview and validation. And storage image into folder and MySQL database by using the below steps:

Install Laravel Fresh App
Setup Database Details
Generate Image Migration & Model
Create Image Upload Route
Create Image Controller
Create Image Upload and Preview Blade View
Start Development Server

https://www.tutsmake.com/laravel-7-6-image-upload-with-preview-validation-tutorial/

#laravel 7 image upload example #laravel upload image to database #how to insert image into database in laravel #laravel upload image to storage #laravel image upload tutorial #image upload in laravel 7/6