Kako izraditi svoju prvu CRUD aplikaciju s Laravel i MySQL

Kroz ovaj tutorial za početnike naučit ćete koristiti Laravel 5.7 - najnoviju verziju jednog od najpopularnijih PHP okvira - za stvaranje CRUD web aplikacije s MySQL bazom podataka od nule. Proći ćemo kroz postupak korak po korak, počevši od instalacije Composer-a (PHP upravitelja paketa) i nastavljajući s implementacijom i posluživanjem vaše aplikacije.

Preduvjeti

Ovaj tutorial pretpostavlja da imate PHP i MySQL instalirane na vašem sustavu. Slijedite upute za vaš operativni sustav da biste ih instalirali.

Također morate biti upoznati s Linuxom / macOS bashom gdje ćemo izvršavati naredbe u ovom vodiču.

Potrebno je poznavanje PHP-a jer se Laravel temelji na PHP-u.

Za razvoj ću koristiti stroj Ubuntu 16.04, tako da naredbe u ovom vodiču ciljaju ovaj sustav, ali trebali biste biti u mogućnosti slijediti ovaj vodič u bilo kojem operativnom sustavu koji koristite.

Instaliranje PHP 7.1

Laravel v5.7 zahtijeva PHP 7.1 ili noviji pa vam je potrebna najnovija verzija PHP-a instalirana na vašem sustavu. Postupak je u većini sustava jednostavan.

Na Ubuntuu možete slijediti ove upute.

Prvo dodajte ondrej/phpPPA koji sadrži najnoviju verziju PHP-a:

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

Zatim instalirajte PHP 7.1 pomoću sljedeće naredbe:

$ sudo apt-get install php7.1

Ako koristite Ubuntu 18.04, PHP 7.2 je uključen u zadano Ubuntu spremište za 18.04, tako da biste ga mogli instalirati pomoću sljedeće naredbe:

$ sudo apt-get install php
Ovaj je vodič testiran na PHP 7.1, ali možete koristiti i novije verzije poput PHP 7.2 ili PHP 7.3

Instaliranje potrebnih modula PHP 7.1

Laravel zahtijeva hrpu modula. Možete ih instalirati pomoću sljedeće naredbe:

$ 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

Instaliranje PHP Composer-a

Započnimo naše putovanje instaliranjem Composer, PHP upravitelja paketa.

Krećite se u svom kućnom direktoriju, a zatim preuzmite program za instaliranje sa službenog web mjesta pomoću curl:

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

Zatim možete instalirati composerglobalno na svoj sustav pomoću sljedeće naredbe:

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

Od pisanja ovog članka, Composer 1.8 bit će instaliran na vašem sustavu. Možete se pobrinuti da vaša instalacija radi kako je očekivano pokretanjem composerna vašem terminalu:

Trebali biste dobiti sljedeći izlaz:

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

Za više informacija pogledajte ovaj vodič.

Ako ste uspješno instalirali Composer u svoj sustav, spremni ste za stvaranje projekta Laravel 5.7.

Instaliranje i stvaranje projekta Laravel 5.7

U ovom ćemo odjeljku predstaviti Laravel, a zatim nastaviti s instaliranjem i izradom Laravel 5.7 projekta.

O Laravelu

Laravel dokumenti to opisuju kao:

Laravel je okvir web aplikacija s izražajnom, elegantnom sintaksom. Vjerujemo da razvoj mora biti ugodno i kreativno iskustvo da bi se uistinu moglo ispuniti. Laravel pokušava ukloniti bol iz razvoja olakšavajući uobičajene zadatke koji se koriste u većini web projekata, kao što su: Laravel je dostupan, ali moćan i pruža alate potrebne za velike, robusne aplikacije.

Generiranje Laravel 5.7 projekta jednostavno je i jednostavno. U svom terminalu pokrenite sljedeću naredbu:

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

Ovo će instalirati laravel/laravelv5.7.19 .

Napomena : Obavezno instalirajte najmanje PHP 7.1 na sustav. Inače, skladatelj će za vaš projekt upotrijebiti Laravel 5.5.

Možete provjeriti instaliranu verziju u svom projektu pomoću:

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

Instaliranje Front-End ovisnosti

U vašem generiranom projektu možete vidjeti da package.jsonse generira datoteka koja uključuje mnoge front-end knjižnice koje vaš projekt može koristiti:

  • axios,
  • bootstrap,
  • cross-env,
  • jquery,
  • mješavina laravel,
  • lodash,
  • popper.js,
  • rješavanje-url-loader,
  • sass,
  • sass-loader,
  • vue.
Napomena : S Laravelom možete koristiti željene knjižnice, a ne one koje su dodane u package.json. Datoteka na vašem Laravel projekt uključuje nekoliko paketa, kao što su i kako pomoći da započnete izgradnju svoje JavaScript prijavu. Također uključuje pomoć u početku rada s Bootstrapom za oblikovanje korisničkog sučelja. Uključuje Laravel Mix koji će vam pomoći da sastavite SASS datoteke u običan CSS.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!