Courses

Flutter 3 Mobile App with Laravel 12 API

Transactions CRUD

You're reading a FREE PREVIEW of a PREMIUM course.

Link to the repository

[Only for premium members]

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 Model:

app/Models/Category.php

use Illuminate\Database\Eloquent\Relations\HasMany;
 
// ...
 
public function transactions(): HasMany
{
return $this->hasMany(Transaction::class);
}

The full lesson is only for Premium Members.
Want to access all 26 text lessons of this course? (116 min read)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord