Friday, 2 August 2024
Monday, 24 June 2024
Laravel Model tutorials
create a laravel project for my table spends
with columns
id bigint autoincre
date date
description varchar(150)
amount float. Use Model, migration, controller with all resources and views.
Solution:
Create the Migration:
Use the make:migration
command to create a migration file for the spends
table:
php artisan make:migration create_spends_table
Define the Schema:
Open the generated migration file in database/migrations
and define the schema for the spends
table:
// database/migrations/xxxx_xx_xx_xxxxxx_create_spends_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSpendsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('spends', function (Blueprint $table) {
$table->bigIncrements('id');
$table->date('date');
$table->string('description', 150);
$table->float('amount');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('spends');
}
}
Run the Migration:
Apply the migration to create the spends
table in your database:
php artisan migrate
Create the Model:
Use the make:model
command to create a model for the spends
table:
php artisan make:model Spend
Define Fillable Attributes:
Open the model file created in app/Models/Spend.php
and define the fillable attributes:
// app/Models/Spend.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Spend extends Model
{
use HasFactory;
protected $fillable = [
'date',
'description',
'amount',
];
}
Define the Controller Methods:
Open the generated controller file in app/Http/Controllers/SpendController.php
and add the methods for CRUD operations:
// app/Http/Controllers/SpendController.php
namespace App\Http\Controllers;
use App\Models\Spend;
use Illuminate\Http\Request;
class SpendController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$spends = Spend::all();
return response()->json($spends);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'date' => 'required|date',
'description' => 'required|string|max:150',
'amount' => 'required|numeric',
]);
$spend = Spend::create($request->all());
return response()->json($spend, 201);
}
/**
* Display the specified resource.
*
* @param \App\Models\Spend $spend
* @return \Illuminate\Http\Response
*/
public function show(Spend $spend)
{
return response()->json($spend);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Spend $spend
* @return \Illuminate\Http\Response
*/
public function edit(Spend $spend)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Spend $spend
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Spend $spend)
{
$request->validate([
'date' => 'required|date',
'description' => 'required|string|max:150',
'amount' => 'required|numeric',
]);
$spend->update($request->all());
return response()->json($spend);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Spend $spend
* @return \Illuminate\Http\Response
*/
public function destroy(Spend $spend)
{
$spend->delete();
return response()->json(null, 204);
}
}
Define the Routes:
Open your routes file (typically routes/web.php
for web routes or routes/api.php
for API routes) and add the routes for the SpendController
:
// routes/web.php or routes/api.php
use App\Http\Controllers\SpendController;
Route::resource('spends', SpendController::class);
Create the Blade View for Listing Data:
Create a Blade view to list all the spends. Let's name it index.blade.php
.
<!-- resources/views/spends/index.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spends List</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h1>Spends List</h1>
<a href="{{ route('spends.create') }}" class="btn btn-primary mb-3">Add Spend</a>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Date</th>
<th>Description</th>
<th>Amount</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach ($spends as $spend)
<tr>
<td>{{ $spend->id }}</td>
<td>{{ $spend->date }}</td>
<td>{{ $spend->description }}</td>
<td>{{ $spend->amount }}</td>
<td>
<a href="{{ route('spends.edit', $spend->id) }}" class="btn btn-warning btn-sm">Edit</a>
<form action="{{ route('spends.destroy', $spend->id) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</body>
</html>
Create the Blade View for Inserting Data:
Create a Blade view to insert new spends. Let's name it create.blade.php
.
<!-- resources/views/spends/create.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Spend</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h1>Add Spend</h1>
<form action="{{ route('spends.store') }}" method="POST">
@csrf
<div class="form-group">
<label for="date">Date</label>
<input type="date" name="date" id="date" class="form-control" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" name="description" id="description" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label for="amount">Amount</label>
<input type="number" name="amount" id="amount" class="form-control" step="0.01" required>
</div>
<button type="submit" class="btn btn-success">Add Spend</button>
<a href="{{ route('spends.index') }}" class="btn btn-secondary">Back to List</a>
</form>
</div>
</body>
</html>
Update the Controller to Return Views:
Update the SpendController
to return these views.
// app/Http/Controllers/SpendController.php
namespace App\Http\Controllers;
use App\Models\Spend;
use Illuminate\Http\Request;
class SpendController extends Controller
{
// Other methods...
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$spends = Spend::all();
return view('spends.index', compact('spends'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('spends.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'date' => 'required|date',
'description' => 'required|string|max:150',
'amount' => 'required|numeric',
]);
Spend::create($request->all());
return redirect()->route('spends.index')->with('success', 'Spend added successfully.');
}
// Other methods...
}
Create the Blade View for Editing Data:
Create a Blade view to edit an existing spend. Let's name it edit.blade.php
.
<!-- resources/views/spends/edit.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Spend</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h1>Edit Spend</h1>
<form action="{{ route('spends.update', $spend->id) }}" method="POST">
@csrf
@method('PUT')
<div class="form-group">
<label for="date">Date</label>
<input type="date" name="date" id="date" class="form-control" value="{{ $spend->date }}" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" name="description" id="description" class="form-control" maxlength="150" value="{{ $spend->description }}" required>
</div>
<div class="form-group">
<label for="amount">Amount</label>
<input type="number" name="amount" id="amount" class="form-control" step="0.01" value="{{ $spend->amount }}" required>
</div>
<button type="submit" class="btn btn-success">Update Spend</button>
<a href="{{ route('spends.index') }}" class="btn btn-secondary">Back to List</a>
</form>
</div>
</body>
</html>
Update the Controller to Return the Edit View and Handle the Update:
Open your SpendController
and add the edit
and update
methods.
// app/Http/Controllers/SpendController.php
namespace App\Http\Controllers;
use App\Models\Spend;
use Illuminate\Http\Request;
class SpendController extends Controller
{
// Other methods...
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Spend $spend
* @return \Illuminate\Http\Response
*/
public function edit(Spend $spend)
{
return view('spends.edit', compact('spend'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Spend $spend
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Spend $spend)
{
$request->validate([
'date' => 'required|date',
'description' => 'required|string|max:150',
'amount' => 'required|numeric',
]);
$spend->update($request->only(['date', 'description', 'amount']));
return redirect()->route('spends.index')->with('success', 'Spend updated successfully.');
}
// Other methods...
}