Destroy model instance with all dependances in Laravel - laravel

I have two models with one-to-many connection. Let it be, for example, User ans UserComment models. When I'm calling User::destroy method, I also want to destroy each UserComment instance with user_id field equal to id of destroyed User. I may simply overload User::destroy method, but I wonder if there is better ways to achieve this.

Yes, the best way (or more efficient) is to do it through migrations. Let's have a little example with User and UserComment. Leave user migration as is. For UserComment do:
Schema::create('usercomments', function(Blueprint $table){
$table->integer('user_id')->unsigned();
....
$table->foreign('user_id', 'fk_user_id')
->references('id')
->on('users')
->onDelete('cascade')
->onUpdate('cascade'); //not needed in your case.
});
Ok, I haven't used this for a long time, so you may check the syntax online. But that's the gist of it.
When you delete a user, all his comments will be delete as well automatically, by your DB.
Goodluck mate!

I would use the database for this (as suggested above by EddyTheDove), but IF you don't want to use the database for this... you can add something to the deleting event of the User model.
EXAMPLE:
protected static function boot() {
parent::boot();
static::deleting(function($user) {
$user->user_comments()->delete();
});
}

Related

Laravel: restore() and update() in one query?

New to laravel, In my case, I have 3 actions (move to active, inactive, and deleted)
when moved to active/inactive, the status column in database is changed,
when deleted, it gets soft deleted (without changing the status column),
Now, when the deleted rows are being moved to active/inactive, I should use restore() and at the same it, update the status column as specified.
But I can't find any docs regarding this use case.
You may write some helper method for Model to do though
I know this is not exactly the answer of your question but using these you can active/inactive your model without knowing about how it works and also it prevents redundant codes all over the project.
use Illuminate\Support\Facades\DB;
protected function toggleStatus($status) {
DB::transaction(function () use($status) {
$this->restore();
$this->update(['status' => $status]);
});
}
public function active() {
$this->toggleStatus('active');
}
public function inactive() {
$this->toggleStatus('inactive');
}

Eloquent model getRawOriginal() returns new values in `updating` observer

I need to compare original model values with changes that are done when update occurs, but I am not able to do that.
My model update code looks like this:
public function update(array $user, int $userId): ?bool
{
return User::find($userId)->update($user);
}
I thought that the best way to capture changes is to use observer and observe updating event, because I assume it's called right before changes are stored in the database. Here is updating method code:
public function updating(User $user)
{
Log::info('Original user', ['original' => $user->getRawOriginal('status')]);
}
I've tried logging a bit and it seems that updating method gets called after the update happens and then when I try to retrieve original model values there it returns new ones, instead of the original ones.
If I use getChanges() method in updating it returns exactly what has changed, so it seems that changes are tracked somehow, but not the original values?
Can someone give me any pointers how to solve this and explain to me why my approach doesn't work?
Update: Code, where I call update, is wrapped with DB transaction methods. After removing them it seems that updating method gets called at the right time and getRawOriginal then returns expected results.
In this case, what are my options? Is there a way to do what I want without removing transactions?
You can add boot method in your model .Both updating and updated trigger while updating .
protected static function boot()
{
parent::boot();
static::updating(function ($model){
echo "updating";
dump($model->getDirty());
dump($model->getRawOriginal('username'));
});
static::updated(function ($model){
echo "updated";
dump($model->getDirty());
dump($model->getRawOriginal('mobile_number'));
});
}

Creating new table in octobercms

I must create new table in octobercms project and I followed documentation and added new migration file inside plugin update file I have create_currency_rates_table.php file and it has this codes
<?php namespace RainLab\User\Updates;
use Schema;
use October\Rain\Database\Updates\Migration;
class CreateCurrencyRateTable extends Migration
{
public function up()
{
Schema::create('currency_rates', function($table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('currency');
});
}
public function down()
{
Schema::drop('currency_rate');
}
}
when I used php artisan october:up it is not detecting new migration. How can I create new table?Can anyone help me?
You also need to update plugins\<author>\<plugin_name>\updates\version.yaml this file and add your file name there as well.
So, in your case, you added a file like create_currency_rates_table.php then you need to add details of your file in version.yaml
for ex:
1.0.1: First version of Demo
1.0.2:
- Description About what is this update about?
- create_currency_rates_table.php
now when you next time just login to backend this table will be created automatically.
if any doubt please comment.

Laravel migration - Update id field from integer auto increment to string

I tried to change id field from Integer auto increment to string but after I run migrate, the structure of MYSQL's not change.
This is my code:
Schema::table('table', function ($table) {
$table->dropPrimary();
$table->string('id', 50)->change()->primary();
});
Please help me, thank you so much.
You should write this. Hopefully this will solve your problem
Schema::table('table', function ($table) {
$table->dropPrimary('id');
$table->string('id', 50)->change()->primary();
});
Also you should check if doctrine/dbal is installed successfully

How to get transaction id after successful subscription

I am working on a platform offering services. When creating a new subscription, a new transaction for the first billing is created. How can I access the transactions id?
I have a form with Braintree's Drop-in UI and my backend looks currently like this:
if (!auth()->user()->subscribed('main')) {
$subscription = auth()->user()->newSubscription('main', 'membership-monthly')->create($request->payment_method_nonce, []);
dd($subscription);
}
This successfully creates a new subscription!
Now I want to access this subscription's first billing transaction's id.
How can I achieve this?
Probably, you should provide a second parameter to create function,
try this:
if (!auth()->user()->subscribed('main')) {
$payload = array();
$subscription = auth()
->user()
->newSubscription('main', 'membership-monthly')
->create($request->payment_method_nonce, $payload);
dd($subscription);
dd($payload);
}
From the Laravel Cashier documentation the database schema looks like this:
Schema::create('subscriptions', function ($table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('name');
$table->string('braintree_id');
$table->string('braintree_plan');
$table->integer('quantity');
$table->timestamp('trial_ends_at')->nullable();
$table->timestamp('ends_at')->nullable();
$table->timestamps();
});
I would assume to get the subscription in your case would be similar to $subscription->braintree_id
If you have an relation between subscription and transactions you need access so :
foreach($subscription->transactions() as $transaction){
//here you access yo transactions id
dd($transaction);
}
I hope that i could help you

Resources