A kezdőknek szánt oktatóanyag során megtanulja használni a Laravel 5.7-et - az egyik legnépszerűbb PHP-keretrendszer legújabb verzióját - egy CRUD webalkalmazás létrehozásához MySQL adatbázissal a semmiből. A folyamatot lépésről lépésre végezzük el, kezdve a Composer (PHP csomagkezelő) telepítésével, és folytatva az alkalmazás megvalósítását és kiszolgálását.
Előfeltételek
Ez az oktatóanyag feltételezi, hogy a rendszerre telepítve van a PHP és a MySQL. Kövesse az operációs rendszer utasításait mindkettő telepítéséhez.
Ismernie kell a Linux / macOS bash-t is, ahol végrehajtjuk a parancsokat ebben az oktatóanyagban.
Szükséges a PHP ismerete, mivel a Laravel a PHP-re épül.
A fejlesztéshez egy Ubuntu 16.04 gépet fogok használni, így az oktatóanyagban szereplő parancsok ezt a rendszert célozzák, de képesnek kell lennie arra, hogy kövesse ezt az oktatóanyagot bármelyik használt operációs rendszerben.
A PHP telepítése 7.1
A Laravel v5.7 PHP 7.1 vagy újabb verziót igényel, ezért a PHP legújabb verziójára van szükség a rendszerre telepítve. A folyamat a legtöbb rendszerben egyszerű.
Az Ubuntuban kövesse ezeket az utasításokat.
Először adja hozzá a ondrej/php
PHP legújabb verzióját tartalmazó PPA-t:
$ sudo add-apt-repository ppa:ondrej/php $ sudo apt-get update
Ezután telepítse a PHP 7.1-et a következő paranccsal:
$ sudo apt-get install php7.1
Ha Ubuntu 18.04-et használ, akkor a PHP 7.2 az alapértelmezett 18.04-es Ubuntu-tárházban található, így a következő paranccsal kell tudni telepíteni:
$ sudo apt-get install php
Ez az oktatóanyag a PHP 7.1 verzióval van tesztelve, de használhat olyan újabb verziókat is, mint a PHP 7.2 vagy a PHP 7.3
A szükséges PHP 7.1 modulok telepítése
A Laravel egy csomó modult igényel. A következő paranccsal telepítheti őket:
$ 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
A PHP Composer telepítése
Kezdjük az utunkat a Composer, a PHP csomagkezelő telepítésével.
Navigáljon a saját könyvtárában, majd töltse le a telepítőt a hivatalos webhelyről curl
:
$ cd ~ $ curl -sS //getcomposer.org/installer -o composer-setup.php
Ezután composer
globálisan telepíthető a rendszerre a következő paranccsal:
$ sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
Jelen írásban a Composer 1.8 telepítve lesz a rendszerére. A composer
terminálon történő futtatással ellenőrizheti, hogy a telepítés a várt módon működik -e:
A következő kimenetet kell kapnia:
______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___// /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/ /_/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
További információkért tekintse meg ezt az oktatóanyagot.
Ha sikeresen telepítette a Composert a rendszerébe, készen áll a Laravel 5.7 projekt létrehozására.
Laravel 5.7 projekt telepítése és létrehozása
Ebben a részben bemutatjuk a Laravel programot, majd folytatjuk a telepítést és egy Laravel 5.7 projekt létrehozását.
Laravelről
A Laravel docs a következőképpen írja le:
A Laravel egy webes alkalmazás keretrendszer, kifejező, elegáns szintaxissal. Úgy gondoljuk, hogy a fejlődésnek élvezetes és kreatív élménynek kell lennie ahhoz, hogy valóban kielégítő legyen. A Laravel megkísérli elhárítani a fejlesztésből fakadó fájdalmat azáltal, hogy megkönnyíti a webes projektek többségében használt közös feladatokat, például: A Laravel hozzáférhető, ugyanakkor hatékony, a nagy, robusztus alkalmazásokhoz szükséges eszközöket kínálja.A Laravel 5.7 projekt létrehozása egyszerű és egyszerű. Futtassa a terminálon a következő parancsot:
$ composer create-project --prefer-dist laravel/laravel laravel-first-crud-app
Ez telepíti a laravel/laravel
v5.7.19 verziót .
A projekt telepített verzióját ellenőrizheti a következők használatával:
$ cd laravel-first-crud-app $ php artisan -V Laravel Framework 5.7.22
Az elülső függőségek telepítése
A létrehozott projektben láthatja, hogy egy package.json
fájl jön létre, amely számos olyan elülső könyvtárat tartalmaz, amelyeket a projektje használhat:
- axios,
- bootstrap,
- cross-env,
- jquery,
- laravel-mix,
- páholy,
- popper.js,
- resol-url-loader,
- sass,
- sass-loader,
- vue.
package.json
.
A package.json
Laravel projekt fájlja tartalmaz néhány csomagot, például, vue
és axios
segítséget nyújt a JavaScript alkalmazás felépítésének megkezdésében.
Ez magában foglalja bootstrap
azt is, hogy segítsen a Bootstrap használatának megkezdésében a felhasználói felület stílusának megalkotásában.
Tartalmazza a Laravel Mix-et, amely segít a SASS fájlok egyszerű CSS-be fordításában.
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!