1586950440
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 accessors
and murators
will 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.
A little briefly accessors
will help us format the data when we get data from the database. Suppose we have a field name
in a table user
and want it to be capitalized when retrieving data. First we need to create a method to define this in the model User
as get
+ field name in uppercase letters
+ Attribute
. 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 route
as 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;
Other than that, accessors
it is murators
used to format data before saving it into a database. To define a murators
similarity with accessors
just another is the prefix would be set
. For example, we will format the field name
to 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 tinker
up to the test App\User::find(1)
, we will see the value of the name
medium will be saved ccc
.
By default, Eloquent will automatically convert two fields created_at
and update_at
into a Carbon instance, and it provides a lot of useful functions. We can also add date attributes using the $date
model
<?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 date
you 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.
By default the timestamps are formatted Y-m-d H:i:s
, you can customize this format by using the attribute dateFormat
in 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';
}
Attributes $cast
help convert attributes to normal data types. The property $cast
is 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 $cast
supports: integer, real, float, double, decimal:<digits>, string, boolean, object, array, collection, date, datetime, and timestamp
. For example, we have the attribute is_admin
stored in the database is 0
and 1
with the data type integer
but 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_admin
as a property of data typeboolean
$user = App\User::find(1);
if ($user->is_admin) {
}
You can define an attribute cast
for your own by creating an implements class from the CastsAttributes
interface. One thing to note is that this newly created class must exist two methods get
and set
with different tasks. The method is get
used to convert data in the database to the data type cast
you define, and the method set
has the opposite task to convert the converted data into the original data type to store in the database. For example, we custom attribute cast
is 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,
];
}
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();
When used cast
with date and datetime data types, we can reformat for this data type
protected $casts = [
'created_at' => 'datetime:Y-m-d',
];
Sometimes you can use both cast
in 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_at
based on the result of the selectRaw statement, which makes sense if we set the data type to last_posted_at
a 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 cast
brings here .
#php #laravel
1625034420
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.
#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
1597817005
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.
Use the below given steps and generate bAR/QR codes in laravel Projects:
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
1627451820
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
You May Also Like :
#laravel accessor and mutator example #laravel accessor #mutator #php laravel #laravel 8 #laravel
1597727551
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.
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
1597563325
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 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