Sådan bygger du din første CRUD-app med Laravel og MySQL
I hele denne tutorial for begyndere lærer du at bruge Laravel 5.7 - den nyeste version af en af de mest populære PHP-rammer - til at oprette en CRUD-webapplikation med en MySQL-database fra bunden. Vi gennemgår processen trin for trin startende med installationen af Composer (PHP-pakkehåndtering) og fortsætter med at implementere og betjene din applikation.
Forudsætninger
Denne vejledning forudsætter, at du har PHP og MySQL installeret på dit system. Følg instruktionerne til dit operativsystem for at installere dem begge.
Du skal også være fortrolig med Linux / macOS bash, hvor vi udfører kommandoerne i denne vejledning.
Kendskab til PHP er påkrævet, da Laravel er baseret på PHP.
Til udvikling bruger jeg en Ubuntu 16.04-maskine, så kommandoerne i denne vejledning er målrettet mod dette system, men du skal kunne følge denne vejledning i ethvert operativsystem, du bruger.
Installation af PHP 7.1
Laravel v5.7 kræver PHP 7.1 eller nyere, så du har brug for den nyeste version af PHP installeret på dit system. Processen er ligetil på de fleste systemer.
På Ubuntu kan du følge disse instruktioner.
Tilføj først ondrej/php
PPA, som indeholder den nyeste version af PHP:
$ sudo add-apt-repository ppa:ondrej/php $ sudo apt-get update
Dernæst skal du installere PHP 7.1 ved hjælp af følgende kommando:
$ sudo apt-get install php7.1
Hvis du bruger Ubuntu 18.04, er PHP 7.2 inkluderet i standard Ubuntu-lageret til 18.04, så du skal kunne installere det ved hjælp af følgende kommando:
$ sudo apt-get install php
Denne tutorial er testet med PHP 7.1, men du kan også bruge nyere versioner som PHP 7.2 eller PHP 7.3
Installation af de krævede PHP 7.1-moduler
Laravel kræver en masse moduler. Du kan installere dem ved hjælp af følgende kommando:
$ sudo apt-get install php7.1 php7.1-cli php7.1-common php7.1-json php7.1-opcache php7.1-mysql php7.1-mbstring php7.1-mcrypt php7.1-zip php7.1-fpm php7.1-xml
Installation af PHP Composer
Lad os starte vores rejse med at installere Composer, PHP-pakkehåndtering.
Naviger i dit hjemmekatalog, og download derefter installationsprogrammet fra det officielle websted ved hjælp af curl
:
$ cd ~ $ curl -sS //getcomposer.org/installer -o composer-setup.php
Du kan derefter installere composer
globalt på dit system ved hjælp af følgende kommando:
$ sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
I skrivende stund vil Composer 1.8 blive installeret på dit system. Du kan sikre dig, at din installation fungerer som forventet ved at køre composer
i din terminal:
Du skal få følgende output:
______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___// /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/ /_/Composer version 1.8.0 2018-12-03 10:31:16Usage: command [options] [arguments]Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information --no-plugins Whether to disable plugins. -d, --working-dir=WORKING-DIR If specified, use the given directory as working directory. -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
For mere information, se denne vejledning.
Hvis du har installeret Composer med succes i dit system, er du klar til at oprette et Laravel 5.7-projekt.
Installation og oprettelse af et Laravel 5.7-projekt
I dette afsnit introducerer vi Laravel og fortsætter derefter med at installere og oprette et Laravel 5.7-projekt.
Om Laravel
Laravel docs beskriver det som:
Laravel er en webapplikationsramme med udtryksfuld, elegant syntaks. Vi mener, at udvikling skal være en fornøjelig og kreativ oplevelse for at være virkelig tilfredsstillende. Laravel forsøger at tage smerten ud af udviklingen ved at lette almindelige opgaver, der bruges i de fleste webprojekter, såsom: Laravel er tilgængelig, men alligevel kraftig, og leverer værktøjer, der er nødvendige til store, robuste applikationer.At generere et Laravel 5.7-projekt er let og ligetil. Kør følgende kommando i din terminal:
$ composer create-project --prefer-dist laravel/laravel laravel-first-crud-app
Dette installerer laravel/laravel
v5.7.19 .
You can verify the installed version in your project using:
$ cd laravel-first-crud-app $ php artisan -V Laravel Framework 5.7.22
Installing the Front-End Dependencies
In your generated project, you can see that a package.json
file is generated which includes many front-end libraries that can be used by your project:
- axios,
- bootstrap,
- cross-env,
- jquery,
- laravel-mix,
- lodash,
- popper.js,
- resolve-url-loader,
- sass,
- sass-loader,
- vue.
package.json
.
The package.json
file in your Laravel project includes a few packages such as vue
and axios
to help you get started building your JavaScript application.
It also includes bootstrap
to help you get started with Bootstrap for styling your UI.
It includes Laravel Mix to help you compile your SASS files to plain CSS.
You need to use npm
to install the front-end dependencies:
$ npm install
After running this command a node_modules
folder will be created and the dependencies will be installed into it.
Creating a MySQL Database
Let’s now create a MySQL database that we’ll use to persist data in our Laravel application. In your terminal, run the following command to run the mysql
client:
$ mysql -u root -p
When prompted, enter the password for your MySQL server when you’ve installed it.
Next, run the following SQL statement to create a db
database:
mysql> create database db;
Open the .env
file and update the credentials to access your MySQL database:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=db DB_USERNAME=root DB_PASSWORD=******
You need to enter the database name, the username and password.
At this point, you can run the migrate
command to create your database and a bunch of SQL tables needed by Laravel:
migrate
command at any other points of your development to add other SQL tables in your database or to later your database if you need to add any changes later.
Creating your First Laravel Model
Laravel uses the MVC architectural pattern to organize your application in three decoupled parts:
- The Model which encapsulates the data access layer,
- The View which encapsulates the representation layer,
- Controller which encapsulates the code to control the application and communicates with the model and view layers.
Wikipedia defines MVC as:
Model–view–controller is an architectural pattern commonly used for developing user interfaces that divides an application into three interconnected parts. This is done to separate internal representations of information from the ways information is presented to and accepted from the user.Now, let’s create our first Laravel Model. In your terminal, run the following command:
$ php artisan make:model Contact --migration
This will create a Contact model and a migration file. In the terminal, we get an output similar to:
Model created successfully. Created Migration: 2019_01_27_193840_create_contacts_table
Open the database/migrations/xxxxxx_create_contacts_table
migration file and update it accordingly:
increments('id'); $table->timestamps(); $table->string('first_name'); $table->string('last_name'); $table->string('email'); $table->string('job_title'); $table->string('city'); $table->string('country'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('contacts'); }}
We added the first_name
, last_name
, email
, job_title
, city
and country
fields in the contacts
table.
You can now create the contacts
table in the database using the following command:
$ php artisan migrate
Now, let’s look at our Contact
model, which will be used to interact with the contacts
database table. Open the app/Contact.php
and update it:
Creating the Controller and Routes
After creating the model and migrating our database, let’s now create the controller and the routes for working with the
Contact
model. In your terminal, run the following command:
$ php artisan make:controller ContactController --resource
Laravel resource routing assigns the typical “CRUD” routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for “photos” stored by your application. Using the make:controller
Artisan command, we can quickly create such a controller.This command will generate a controller at app/Http/Controllers/PhotoController.php
. The controller will contain a method for each of the available resource operations.Open the app/Http/Controllers/ContactController.php
file. This is the initial content:
The ContactController
class extends Controller
class available from Laravel and defines a bunch of methods which will be used to do the CRUD operations against the Contact
model.
You can read the role of the method on the comment above it.
Now we need to provide implementations for these methods.
But before that, let’s add routing. Open the routes/web.php
file and update it accordingly:
Using the resource()
static method of Route
, you can create multiple routes to expose multiple actions on the resource.
These routes are mapped to various ContactController
methods which we will need to implement in the next section:
GET/contacts
, mapped to the index()
method,
GET /contacts/create
, mapped to the create()
method,
POST /contacts
, mapped to the store()
method,
GET /contacts/{contact}
, mapped to the show()
method,
GET /contacts/{contact}/edit
, mapped to the edit()
method,
PUT/PATCH /contacts/{contact}
, mapped to the update()
method,
DELETE /contacts/{contact}
, mapped to the destroy()
method.
These routes are used to serve HTML templates and also as API endpoints for working with the Contact
model.
Note: If you want to create a controller that will only expose a RESTful API, you can use the apiResource
method to exclude the routes that are used to serve the HTML templates:Route::apiResource('contacts', 'ContactController');
Implementing the CRUD Operations
Let’s now implement the controller methods alongside the views.
C: Implementing the Create Operation and Adding a Form
The ContactController
includes
- the
store()
method that maps to the POST /contacts
API endpoint which will be used to create a contact in the database, and
- the
create()
that maps to the GET /contacts/create
route which will be used to serve the HTML form used to submit the contact to POST /contacts
API endpoint.
Let’s implement these two methods.
Re-open the app/Http/Controllers/ContactController.php
file and start by importing the Contact
model:
use App\Contact;
Next, locate the store()
method and update it accordingly:
public function store(Request $request) { $request->validate([ 'first_name'=>'required', 'last_name'=>'required', 'email'=>'required' ]); $contact = new Contact([ 'first_name' => $request->get('first_name'), 'last_name' => $request->get('last_name'), 'email' => $request->get('email'), 'job_title' => $request->get('job_title'), 'city' => $request->get('city'), 'country' => $request->get('country') ]); $contact->save(); return redirect('/contacts')->with('success', 'Contact saved!'); }
Next, locate the create()
method and update it:
public function create() { return view('contacts.create'); }
The create()
function makes use of the view()
method to return the create.blade.php
template which needs to be present in the resources/views
folder.
Before creating the create.blade.php
template we need to create a base template that will be extended by the create template and all the other templates that will create later in this tutorial.
In the resources/views
folder, create a base.blade.php
file:
$ cd resources/views $ touch base.blade.php
Open the resources/views/base.blade.php
file and add the following blade template:
Laravel 5.7 & MySQL CRUD Tutorial @yield('main')
Now, let’s create the create.blade.php
template. First, create a contacts folder in the views folder:
$ mkdir contacts
Next, create the template
$ cd contacts $ touch create.blade.php
Open the resources/views/contacts/create.blade.php
file and add the following code:
@extends('base')@section('main') Add a contact
@if ($errors->any())
@foreach ($errors->all() as $error)
- {{ $error }}
@endforeach
@endif @csrf First Name: Last Name: Email: City: Country: Job Title: Add contact @endsection
This is a screenshot of our create form!

Fill out the form and click on the Add contact button to create a contact in the database. You should be redirected to /contacts route which doesn’t have a view associated to it yet.
R: Implementing the Read Operation and Getting Data
Next, let’s implement the read operation to get and display contacts data from our MySQL database.
Go to the app/Http/Controllers/ContactController.php
file, locate the index()
method and update it:
public function index() { $contacts = Contact::all(); return view('contacts.index', compact('contacts')); }
Next, you need to create the index template. Create a resources/views/contacts/index.blade.php
file:
$ touch index.blade.php
Open the resources/views/contacts/index.blade.php
file and add the following code:
@extends('base')@section('main') Contacts
@foreach($contacts as $contact)
@endforeach
ID
Name
Email
Job Title
City
Country
Actions
{{$contact->id}}
{{$contact->first_name}} {{$contact->last_name}}
{{$contact->email}}
{{$contact->job_title}}
{{$contact->city}}
{{$contact->country}}
id)}}">Edit
id)}}" method="post"> @csrf @method('DELETE') Delete
@endsection
U: Implementing the Update Operation
Next, we need to implement the update operation. Go to the app/Http/Controllers/ContactController.php
file, locate the edit($id)
method and update it:
public function edit($id) { $contact = Contact::find($id); return view('contacts.edit', compact('contact')); }
Next, you need to implement the update()
method:
public function update(Request $request, $id) { $request->validate([ 'first_name'=>'required', 'last_name'=>'required', 'email'=>'required' ]); $contact = Contact::find($id); $contact->first_name = $request->get('first_name'); $contact->last_name = $request->get('last_name'); $contact->email = $request->get('email'); $contact->job_title = $request->get('job_title'); $contact->city = $request->get('city'); $contact->country = $request->get('country'); $contact->save(); return redirect('/contacts')->with('success', 'Contact updated!'); }
Now, you need to add the edit template. Inside the resources/views/contacts/
, create an edit.blade.php
file:
$ touch edit.blade.php
Open the resources/views/contacts/edit.blade.php
file and add this code:
@extends('base') @section('main') Update a contact
@if ($errors->any())
@foreach ($errors->all() as $error)
- {{ $error }}
@endforeach
@endif id) }}"> @method('PATCH') @csrf First Name: first_name }} /> Last Name: last_name }} /> Email: email }} /> City: city }} /> Country: country }} /> Job Title: job_title }} /> Update @endsection
D: Implementing the Delete Operation
Finally, we’ll proceed to implement the delete operation. Go to the app/Http/Controllers/ContactController.php
file, locate the destroy()
method and update it accordingly:
public function destroy($id) { $contact = Contact::find($id); $contact->delete(); return redirect('/contacts')->with('success', 'Contact deleted!'); }
You can notice that when we redirect to the /contacts
route in our CRUD API methods, we also pass a success message but it doesn't appear in our index
template. Let's change that!
Go to the resources/views/contacts/index.blade.php
file and add the following code:
@if(session()->get('success')) {{ session()->get('success') }} @endif
We also need to add a button to takes us to the create form. Add this code below the header:
New contact
This is a screenshot of the page after we created a contact:

Conclusion
We’ve reached the end of this tutorial. We created a CRUD application with Laravel 5.7, PHP 7.1 and MySQL.
Hope you enjoyed the tutorial and see you in the next one!