dev-resources.site
for different kinds of informations.
Why Are People Using Laravel?
PHP is dead. Or is it?
For whatever reason, I've heard many people talk about Laravel here lately, the most popular PHP framework. I figured I'd play around with it and see the buzz. I enjoyed it!
First, we need a database. We'll use docker to run a MySQL database.
# Create a docker network
docker network create localnetwork
# Run a MySQL database
docker run -d --name mysql-container --network=localnetwork -e MYSQL_ROOT_PASSWORD=password -p 3306:3306 mysql:latest
# Run phpMyAdmin
docker run -d --name phpmyadmin-container --network=localnetwork -e PMA_HOST=mysql-container -e PMA_PORT=3306 -p 8080:80 phpmyadmin/phpmyadmin:latest
Next, install Composer. If you have a Mac, use homebrew.
install composer
Use Composer to generate a fresh laravel project.
composer create-project --prefer-dist laravel/laravel laravel-api
Update your database credentials in the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crud_app
DB_USERNAME=root
DB_PASSWORD=password
Serve it up.
php artisan serve
Create routes/api.php.
<?php
use App\Http\Controllers\ThingController;
Route::get('/things', [ThingController::class, 'index']);
Route::get('/things/{id}', [ThingController::class, 'show']);
Route::post('/things', [ThingController::class, 'store']);
Route::put('/things/{id}', [ThingController::class, 'update']);
Route::delete('/things/{id}', [ThingController::class, 'destroy']);
Update app.php so that your routes are defined.
Next, have Laravel generate your controller: php artisan make:controller ThingController
Generate your model: php artisan make:model Thing
Update your model with protected $guarded = [];
This tells the database to accept everything except what you specify in the array.
Define your CRUD operations in your ThingController.
<?php
namespace App\Http\Controllers;
use App\Models\Thing;
use Illuminate\Http\Request;
class ThingController extends Controller
{
public function index()
{
$things = Thing::all();
return response()->json($things);
}
public function show($id)
{
$thing = Thing::find($id);
return response()->json($thing);
}
public function store(Request $request)
{
$thing = Thing::create($request->all());
return response()->json($thing, 201);
}
public function update(Request $request, $id)
{
$thing = Thing::find($id);
$thing->update($request->all());
return response()->json($thing, 200);
}
public function destroy($id)
{
Thing::destroy($id);
return response()->json(null, 204);
}
}
Run php artisan migrate
to setup the database. Say 'Yes'.
Next login to phpMyAdmin and create the things table.
Note that we set the id to auto-increment.
Now use postman to create some 'things'.
Now, let's get the 'things'.
GitHub repo: https://github.com/jWatsonDev/sample-laravel-crud
Fin.
Featured ones: