Home >Database >Mysql Tutorial >Laravel Eloquent ORM in Bangla Part-Replicating Models)
Laravel Eloquent's Replicating Models can create a new record using all or part of a model's data. It is used to make a semi-copy without re-inserting the previous data.
This can be done using Laravel's replicate()
method. Below are some examples:
1. Replicating the model using the replicate()
method
replicate()
method creates a copy of the model, but omits the model's id
and timestamps
(unless you save them). You can also replicate specific fields.
<code class="language-php">use App\Models\Post; $post = Post::find(1); // মূল পোস্ট খুঁজে বের করা // পোস্ট রিপ্লিকেট করা $newPost = $post->replicate(); // অতিরিক্ত ক্ষেত্রের মান পরিবর্তন $newPost->title = 'নতুন পোস্ট'; $newPost->status = 'ড্রাফট'; // নতুন পোস্ট সংরক্ষণ $newPost->save();</code>
How does it work?
replicate()
method creates a new model by copying the data from the original model.title
, status
etc.save()
method.2. Replicating
excluding some fields Thereplicate()
method can be replicated by omitting specific fields using .except()
or .makeHidden()
.
<code class="language-php">use App\Models\Post; $post = Post::find(1); // `created_at` এবং `updated_at` ক্ষেত্র বাদ দিয়ে রিপ্লিকেট করা $newPost = $post->replicate()->makeHidden(['created_at', 'updated_at']); $newPost->save();</code>
This way other data can be copied except created_at
and updated_at
.
3. Replicating relational model
If a model is related to another model (One-to-Many, Many-to-Many), then those related models can also be copied. For example, if a post has many comments:
<code class="language-php">use App\Models\Post; $post = Post::find(1); // মূল পোস্ট খুঁজে বের করা // পোস্ট রিপ্লিকেট করা $newPost = $post->replicate(); // অতিরিক্ত ক্ষেত্রের মান পরিবর্তন $newPost->title = 'নতুন পোস্ট'; $newPost->status = 'ড্রাফট'; // নতুন পোস্ট সংরক্ষণ $newPost->save();</code>
This will add all comments on the original post to the new post.
4. Cascade Replication (Cascade Replication)
Use cascade replication to automatically replicate related models.
<code class="language-php">use App\Models\Post; $post = Post::find(1); // `created_at` এবং `updated_at` ক্ষেত্র বাদ দিয়ে রিপ্লিকেট করা $newPost = $post->replicate()->makeHidden(['created_at', 'updated_at']); $newPost->save();</code>
5. Replicating
excluding specified fields To copy fields other thanid
field:
<code class="language-php">use App\Models\Post; $post = Post::find(1); // পোস্ট রিপ্লিকেট করা $newPost = $post->replicate(); // সম্পর্কিত মন্তব্য কপি করা $newPost->comments = $post->comments; $newPost->save();</code>
6. replicate()
and Validation
replicate()
Applies the original model's validation rule to the new model.
These examples show various uses of the replicate()
method. These can be modified according to your needs.
The above is the detailed content of Laravel Eloquent ORM in Bangla Part-Replicating Models). For more information, please follow other related articles on the PHP Chinese website!