Kuidas luua oma esimene CRUD-rakendus Laraveli ja MySQL-iga

Selles algajatele mõeldud õpetuses õpitakse kasutama Laravel 5.7 - ühe populaarseima PHP raamistiku uusimat versiooni - MySQL andmebaasiga CRUD veebirakenduse loomiseks nullist. Käime protsessi samm-sammult läbi, alustades Composeri (PHP paketihalduri) installimisest ja jätkates teie rakenduse juurutamise ja teenindamisega.

Eeldused

Selles õpetuses eeldatakse, et teie arvutisse on installitud PHP ja MySQL. Mõlemate installimiseks järgige oma operatsioonisüsteemi juhiseid.

Samuti peate olema tuttav Linuxi / macOS bashiga, kus täidame selle õpetuse käske.

Vajalik on PHP-ga tuttav, kuna Laravel põhineb PHP-l.

Arendamiseks kasutan Ubuntu 16.04 masinat, nii et selles õpetuses olevad käsud on suunatud sellele süsteemile, kuid peaksite saama seda õpetust järgida igas kasutatavas operatsioonisüsteemis.

PHP installimine 7.1

Laravel v5.7 nõuab PHP 7.1 või uuemat versiooni, nii et teil on vaja oma süsteemi installida uusim PHP versioon. Protsess on enamikus süsteemides lihtne.

Ubuntus saate järgida neid juhiseid.

Esmalt lisage ondrej/phpPPA, mis sisaldab PHP uusimat versiooni:

$ sudo add-apt-repository ppa:ondrej/php $ sudo apt-get update

Järgmisena installige PHP 7.1 järgmise käsu abil:

$ sudo apt-get install php7.1

Kui kasutate Ubuntu 18.04, lisatakse PHP 7.2 Ubuntu vaikehoidlasse 18.04 jaoks, nii et peaksite saama selle installida järgmise käsu abil:

$ sudo apt-get install php
Seda õpetust testitakse PHP 7.1-ga, kuid võite kasutada ka uuemaid versioone nagu PHP 7.2 või PHP 7.3

Nõutavate PHP 7.1 moodulite installimine

Laravel vajab hunnikut mooduleid. Saate need installida järgmise käsu abil:

$ 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

PHP Composeri installimine

Alustame teekonda PHP paketihalduri Composeri installimisega.

Navigeeri oma kataloogi, siis alla paigaldaja ametlikul kodulehel kasutades curl:

$ cd ~ $ curl -sS //getcomposer.org/installer -o composer-setup.php

Seejärel saate composeroma süsteemi globaalselt installida järgmise käsu abil:

$ sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

Sellest kirjutamisest alates installitakse teie süsteemi Composer 1.8. composerTerminalis käivitades saate veenduda, et teie install toimib ootuspäraselt :

Peaksite saama järgmise väljundi:

______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___// /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/ /_/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

Lisateabe saamiseks vaadake seda õpetust.

Kui olete Composeri oma süsteemi edukalt installinud, olete valmis looma projekti Laravel 5.7.

Laraveli 5.7 projekti installimine ja loomine

Selles jaotises tutvustame Laraveli ja jätkame seda Laraveli 5.7 projekti installimiseks ja loomiseks.

Laraveli kohta

Laraveli dokumendid kirjeldavad seda järgmiselt:

Laravel on ekspressiivse ja elegantse süntaksiga veebirakenduste raamistik. Usume, et tõeliselt rahuldustpakkuv areng peab olema nauditav ja loominguline kogemus. Laravel üritab leevendada arengust tulenevat valu, hõlbustades enamikus veebiprojektides kasutatavaid tavalisi ülesandeid, näiteks: Laravel on ligipääsetav, kuid samas võimas, pakkudes tööriistu, mis on vajalikud suurte ja jõuliste rakenduste jaoks.

Laraveli 5.7 projekti genereerimine on lihtne ja arusaadav. Käivitage oma terminalis järgmine käsk:

$ composer create-project --prefer-dist laravel/laravel laravel-first-crud-app

See installib laravel/laravelv5.7.19 .

Märkus . Veenduge, et teie süsteemi oleks installitud vähemalt PHP 7.1. Vastasel juhul kasutab helilooja teie projekti jaoks Laraveli 5.5.

Oma projekti installitud versiooni saate kontrollida järgmiselt:

$ cd laravel-first-crud-app $ php artisan -V Laravel Framework 5.7.22

Esiosa sõltuvuste installimine

Teie loodud projektis näete, et package.jsongenereeritakse fail, mis sisaldab paljusid esiotsa teeke, mida teie projekt saab kasutada:

  • aksiosid,
  • bootstrap,
  • cross-env,
  • jquery,
  • laravel-mix,
  • lodža,
  • popper.js,
  • resolur-url-loader,
  • sass,
  • sass-laadur,
  • vue.
Märkus . Laraveli abil saate kasutada eelistatud teeke, mitte ainult neid, millele on lisatud package.json. Fail oma Laravel projekt hõlmab mõned paketid nagu ja aidata teil alustada hoone teie JavaScript taotluse. See hõlmab ka teie kasutajaliidese kujundamisel Bootstrapi kasutamist. See sisaldab Laraveli segu, mis aitab teil oma SASS-faile tavalisse CSS-i kompileerida.package.jsonvueaxios bootstrap

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.

Note : You need to have Node.js and npm installed on your system before you can install the front-end dependencies.

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:

Note : You can run the 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!