1. Stwórz model
php artisan make:model Company -m
wynik
INFO Model [app/Models/Company.php] created successfully. INFO Migration [database/migrations/2024_04_21_085712_create_companies_table.php] created successfully.
2. Aktualizuj strukturę tabeli w pliku database/migrations/2024_04_21_085712_create_companies_table.php
public function up() { Schema::create('companies', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->string('address'); $table->timestamps(); }); }
3. Aktualizuj pola w app/Models/Company.php
... class Company extends Model { use HasFactory; protected $fillable = ['name', 'email', 'address']; }
4. Uruchom migrację aby stworzyć tabelę w bazie:
php artisan migrate
wynik
INFO Preparing database. Creating migration table ............................................................................................................... 28ms DONE INFO Running migrations. 2024_04_21_085712_create_companies_table ............................................................................................... 23ms DONE
5. Stwórz kontroler
php artisan make:controller CompanyController
wynik
INFO Controller [app/Http/Controllers/CompanyController.php] created successfully.
6. Dodaj wymagane funkcje w kontrolerze app/Http/controllers/CompanyController.php
namespace App\Http\Controllers; use App\Models\Company; use Illuminate\Http\Request; class CompanyController extends Controller { public function index() { $companies = Company::orderBy('id', 'desc')->paginate(5); return view('companies.index', compact('companies')); } public function create() { return view('companies.create'); } public function store(Request $request) { $request->validate([ 'name' => 'required', 'email' => 'required', 'address' => 'required', ]); Company::create($request->post()); return redirect()->route('companies.index')->with('success', 'Company has been created successfully.'); } public function show(Company $company) { return view('companies.show', compact('company')); } public function edit(Company $company) { return view('companies.edit', compact('company')); } public function update(Request $request, Company $company) { $request->validate([ 'name' => 'required', 'email' => 'required', 'address' => 'required', ]); $company->fill($request->post())->save(); return redirect()->route('companies.index')->with('success', 'Company Has Been updated successfully'); } public function destroy(Company $company) { $company->delete(); return redirect()->route('companies.index')->with('success', 'Company has been deleted successfully'); } }
7. Dodaj trasy w routes/web.php
Route::resource('companies', CompanyController::class);
8. Dodaj widoki
resources/views/companies/index.blade.php resources/views/companies/create.blade.php resources/views/companies/edit.blade.php resources/views/companies/show.blade.php
Źródło: https://techvblogs.com/blog/laravel-10-crud-example-tutorial-for-beginners