Skip to main content

Transactions CRUD

Premium
4 min read

In this lesson, we will repeat most of the steps we made for our Categories CRUD. But this time, we will create Transactions CRUD. Here's a quick overview:

  • Creating Models, Migrations
  • Creating Request classes
  • Creating TransactionController with CRUD methods
  • Creating TransactionResource
  • Adding API routes

So, let's dive into it.


Creating Models, Migrations

Let's start by creating our Model with migrations:

php artisan make:model Transaction -m

Then, let's update the migration file:

Migration

Schema::create('transactions', function (Blueprint $table) {
$table->id();
$table->foreignId('category_id')->constrained();
$table->foreignId('user_id')->nullable()->constrained();
$table->date('transaction_date');
$table->integer('amount');
$table->string('description');
$table->timestamps();
});

Our Model, which will have an amount attribute that will be cast to cents:

app/Models/Transaction.php

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
 
class Transaction extends Model
{
protected $fillable = [
'category_id',
'user_id',
'transaction_date',
'amount',
'description',
];
 
protected function casts()
{
return [
'transaction_date' => 'date',
];
}
 
protected function amount(): Attribute
{
return Attribute::make(
get: fn($value) => $value / 100,
set: fn($value) => $value * 100,
);
}
 
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
 
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
}

Because our Transactions are tied with Categories, we need to add a relationship to the categories...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 41 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

JV
Johan van den Broek ✓ Link copied!

Remember to run

php artisan migrate

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.