laravel models

 accessors get,mutators set

fillable

protected $table

rules


scope 

repeated functioins

relatiiosn 

getters 

setters


 




=

I love Eloquent Local Scopes. Just wrote this code. So good, especially if you can combine a few of them and write this elegant piece of code in the Controller.




⚡ Supercharge your #Laravel model events with queueable closures! 🚀 Learn how to optimize tasks using queueable closures for background processing. 🪄 Boost performance effortlessly. 👨‍💻🔥 #Laravel #PHP #Tips 🤯






protected $connection

protected $database

protected $primaryKey='mcr_key';

public $incrimenting =false;

protected  $incrimenting =false;

protected $keyType = 'string';

public const CREATED_AT = 'new_created_at';

public const UPDATED_AT = 'new_updated_at';

protected $conection = 'sqlite';

protected $attirbutes = ['car_type',='sedan',];

protected $fillable = ['user_id','car_type','contact'];

<?php

namespace App\Enums;

enum StatusEnum: string {
    case Pending = 'pending';
    case Active = 'active';
    case Inactive = 'inactive';
}

 protected $fillable = [
        'name',
        'email',
        'status',
    ];

    protected $casts = [
        'status' => StatusEnum::class,
    ];

Laravel Pro Tip: ⚙️ Fine-tune Input Trimming & Normalization! Simplify data handling effortlessly with default behavior or 🎛️ customize it to fit your needs. 💡




 Just discovered a handy Laravel tip! 🎉

Did you know you can use mergeCasts and withCasts for dynamic attribute casting


 





sssssss
https://www.facebook.com/LaravelErrors?__cft__[0]=AZVqJLPVWp5lL3aYgM0N0oqle7HwOj_-TelYaCTp2-3iWNGPOBhG_8WDAA11j37LhQOIZYlr2_I3Ql9Zc7NkDe4bS87EaQxvpaEebNBomMqzOhX5e4BJXI_FL_GjgUD0ZFfbA3ZmAdIT3C3AIQ7D2xx4gmUOuveaGV6UBxRl2N69Vw&__tn__=-UC*F



use has extended relation ships






laravel pacakge
https://github.com/MrPunyapal/laravel-extended-relationships?fbclid=IwAR0zWRWPdElYKUWs05UjO_Fl6OqZ0dd9hLA95xyKJ5UbV_uq-fv9UjFEHYU_aem_AVuheJs_VJvJfrBdIxZ5jAfVvPlaNr0KqcqocJMsp_nQKdP41tZDQJRXDXT-PFI8JhfHaFtn9Qo9xCM-dp-wuz17
scope
global scope


s





locla scope









==

If you notice that you use same relationship often with additional "where" or "orderBy" condition, you can create a separate relationship method.
$this->approvedComments()->latest()?
scope



getters setters
diff for humans
carbon


SCOPES
REUSABLE QUERIES

public function scopeActive($query)
{
return $query->where('status', 'active');
}

// Usage:
$activeUsers = User::active()->get();
// Product.php (Eloquent Model)

public function scopeByCategory($query, $categoryId)
{
return $query->where('category_id', $categoryId);
}

// Usage:
$categoryProducts = Product::byCategory(1)->get();


public function scopePublishedBetween($query, $startDate, $endDate)
{
return $query->whereBetween('published_at', [$startDate, $endDate]);
}

// Usage:
$postsBetweenDates = Post::publishedBetween('2023-01-01', '2023-07-31')->get();


afterquery


BEFORE UPDATE OR AFTER UPDATE IN LARAVGEL 


In Laravel, you can perform actions before or after updating a model using the model's events. Laravel provides various events that you can hook into, such as creating, created, updating, updated, saving, saved, etc. You can use these events to execute code before or after specific model actions.

Here's an example of how to define and use the updating and updated events in a Laravel model:

  1. Define the events in your model's boot method:

    php
    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

    class YourModel extends Model
    {
        protected static function boot()
        {
            parent::boot();

            static::updating(function ($model) {
                // Code to execute before updating
                // You can access the model's properties using $model->propertyName
                // For example: $model->name, $model->email, etc.
            });

            static::updated(function ($model) {
                // Code to execute after updating
                // You can access the model's properties using $model->propertyName
                // For example: $model->name, $model->email, etc.
            });
        }
    }

  2. In the code above, replace YourModel with the actual name of your model class.

  3. Inside the updating and updated event callbacks, you can write the code you want to execute before or after the model is updated. You can access the model's properties using $model->propertyName.

For example, if you want to log when a model is updated, you can do something like this:

php
static::updating(function ($model) {
$changes = $model->getDirty();
foreach ($changes as $key => $value) {
Log::info("Model {$model->getTable()} updated: Changed $key from {$model->getOriginal($key)} to $value");
}
});

In this example, we log the changes made to the model in the updating event, accessing the original values using $model->getOriginal($key) and the new values using $value.

Remember to import the Log facade at the top of your model file if you're using logging (use Illuminate\Support\Facades\Log;). Also, don't forget to configure your logging settings in config/logging.php if you haven't already.

===
writea  aquery inside of eager loading 
closuer function 



laravel observers
https://webdevelopersera.blogspot.com/2023/06/observers-in-laravel.html
=========================================================

use SoftDeletes;

    public const NUMBER_FILE_DELETES = 10;

controller
 $fileName = $disk->putFile(User::FOLDER_UPLOADS, $request->file('avatar'));
  public const FOLDER_UPLOADS = '/uploads/users';
  /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'avatar', 'password'];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Set permissions guard to API by default
     * @var string
     */
    protected $guard_name = 'api';
public function isAdmin(): bool
    {
        foreach ($this->roles as $role) {
            if ($role->isAdmin()) {
                return true;
            }
        }

        return false;
    }

 if ($user->isAdmin()) {
                return $this->jsonMessage(trans('error.is_admin'), false, 403);
            }
for seperate request

public function __construct()
    {
        $this->middleware('permission:' . \ACL::PERMISSION_VISIT, ['only' => ['index']]);
        $this->middleware('permission:' . \ACL::PERMISSION_CREATE, ['only' => ['store']]);
        $this->middleware('permission:' . \ACL::PERMISSION_EDIT, ['only' => ['show', 'update']]);
        $this->middleware('permission:' . \ACL::PERMISSION_DELETE, ['only' => ['destroy']]);
    }



with pivot and with casts


💡Folks, when you can't avoid having single word models, you can alias your relations, and use each method for a different purpose. Especially useful for BelongsTo, where one method can be used when reading/displaying data, whilst the other is used for quering.


==
Laravel models, you can define a broad range of functionality that encapsulates access and manipulation of the data associated with the model. Here's an overview of various elements you might typically include in a Laravel model:

1. Attribute Casting
Automatically cast attributes to a certain type (e.g., casting a JSON string from the database to an array in PHP).
php
Copy code
protected $casts = [
    'is_active' => 'boolean',
    'settings' => 'array'
];
2. Database Table and Connection
Explicitly specify the database table and/or connection that the model should use.
php
Copy code
protected $table = 'my_posts'; // Custom table name
protected $connection = 'sqlite'; // Custom database connection
3. Fillable and Guarded Attributes
Control which attributes should be mass-assignable.
php
Copy code
protected $fillable = ['name', 'email', 'password'];
// or
protected $guarded = ['id'];
4. Date Mutators
Convert attributes to instances of Carbon/DateTime automatically.
php
Copy code
protected $dates = ['created_at', 'updated_at'];
5. Relationships
Define methods to set up relationships like one-to-one, one-to-many, many-to-many, etc.
php
Copy code
public function posts() {
    return $this->hasMany(Post::class);
}
6. Accessors and Mutators
Getters and setters for value transformation before saving to and after reading from a database.
php
Copy code
public function getPasswordAttribute($value) {
    return decrypt($value);
}

public function setPasswordAttribute($value) {
    $this->attributes['password'] = encrypt($value);
}
7. Query Scopes
Define local scopes for common queries which can be chained in query operations.
php
Copy code
public function scopeActive($query) {
    return $query->where('active', 1);
}
8. Business Logic
Methods that encapsulate business logic specific to the model.
php
Copy code
public function deactivate() {
    $this->active = 0;
    return $this->save();
}
9. Events
Model events like creating, updating, deleting, etc., that allow hooking into model lifecycle events.
php
Copy code
protected static function boot() {
    parent::boot();

    static::creating(function ($model) {
        // Called before creating a model
    });
}
10. Route Key Name
Customize the route key to something other than the primary key.
php
Copy code
public function getRouteKeyName() {
    return 'slug';
}
11. Eloquent Serialization
Control what attributes are included in the JSON representation of the model.
php
Copy code
protected $hidden = ['password'];
protected $appends = ['is_admin'];
12. Eloquent API Resources
Although not part of the model, they are closely related. API resources allow you to transform and format model data when it’s being returned via an API.
13. Performance Optimizations
Use settings like $touches, $with, $withCount to manage relationship loading and caching.
php
Copy code
protected $touches = ['user'];
protected $with = ['comments'];
protected $withCount = ['comments'];
14. Soft Deletes
Enable soft deletes to allow restoring "deleted" records.
php
Copy code
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
}
15. Global Scopes
Define global scopes that are automatically applied to all queries for the model's table.
php
Copy code
protected static function boot() {
    parent::boot();

    static::addGlobalScope('age', function (Builder $builder) {
        $builder->where('age', '>', 18);
    });
}
Each of these functionalities allows you to handle different aspects of data management within your application, making models a central component of the Laravel framework's Eloquent ORM and a powerful tool for data abstraction and encapsulation.








No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...