PHP & Web Development Blogs

Search Results For: composer
Showing 6 to 10 of 10 blog articles.
11630 views · 5 years ago
Creating a Tiny Blog Management system in Laravel 5.7

Hey There,
I am expecting you are familiar with PHP. In this post I will be using the Laravel framework to create a small blog system. I am showing here very simple steps to create blogs, If you want this complete code then please message me.
What are major Prequisites for Laravel:
* PHP version >= 5.6
* Composer should be installed in system

Create a project with name tiny_blog with following command

composer create-project laravel/laravel --prefer-dist tiny_blog


enter into the laravel project

cd tiny_blog


create a migration file using following artisan command
<pre>php artisan make:migration create_blog_table</pre>
After this command you will found a new file created in database/migrations folder in your project, Just edit the file having 'create_blog_table' appended in its name

Now replace following code to create table schema with function up(), So now the method will look like following:

public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('category');
$table->string('title');
$table->text('description');
$table->timestamps();
});

}


replace following snippet with down method, it will look like following:

public function down()
{
Schema::dropIfExists('blogs');
}


Its time to run the migration file we have created

php artisan migrate



After running,It will create the blogs table in database.Now time to create form and insert data into the table

Laravel itsef provide authentication , use following artisan command :

php artisan make:auth


Now start Larvel:

php artisan serve


it will start the laravel development server at http://127.0.0.1:8000


Now if you run that url the basic default ui will be created and login & register link you can see in Top right position of header

You can register and login now.this feature is provided by authentication module.
Now we need to create a controller for manage blogs with following command:

php artisan make:controller BlogController


will create a file namedBlogController.php in** app/HTTP/controllers** folder location

Now we need to create a Model also, use following command

php artisan make:model Blog


will create a file namedBlog.php in app folder location

Now in Controller we need to create a method for create blogs and available that method in Routes to access it via url. Just editroutes/web.php file and add the following line

Route::get('blog/create','BlogController@createBlog');

/create/blog/ will be url route that land on Blog Controller's createBlog method using get method.

Now before running this route just go to the app/Http/Controllers folder and Edit BlogController.php file and Add the createBlog method in that class as following

public function createBlog()
{
return view('blog.create');
}


This code will try to load the view from/resources/views/blog/create.blade.php

In Laravel blade is a template engine. As we had not created the view file yet, so we need to create a blog folder inside/resources/views/ folder then inside blog folder create a file create.blade.php with following form

@extends('layouts.app')

@section('content')
<div class="container">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div><br />
@endif
<div class="row">
<form method="post" action="{{url('blog/create')}}">
<div class="form-group">
<input type="hidden" value="{{csrf_token()}}" name="_token" />
<label for="title">Title:</label>
<input type="text" class="form-control" name="title"/>
</div>
<div class="form-group">
<label for="title">Category/Tags:</label>
<input type="text" class="form-control" name="category"/>
</div>
<div class="form-group">
<label for="description">Description:</label>
<textarea cols="10" rows="10" class="form-control" name="description"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
@endsection



Now we need to add a additional route to handle the post request on blog/create route, Just edit routes/web.php file and just add following line in last:

Route::post('blog/create','BlogController@saveBlog'); 


post route to handle the form post on route blog/create


Now create a method name saveBlog to save the user input data in the form
 public function saveBlog(Request $request)
{
$blog = new Blog();

$this->validate($request, [
'title'=>'required',
'category'=>'required',
'description'=> 'required'
]);

$blog->createBlog($request->all());
return redirect('blog/index')->with('success', 'New blog has been created successfully :)'); }


Notice This method is using Blog object that we don't know that where it comes from? , So to make above code working we need to include the model which we created earlier need to include in our controller file So use following code to include it before the class created.

use App\Blog;


Now following line shows that there is a method named createBlog in Model(app/Blog.php), but in actual it is not there:

$blog->createBlog($data);



So go to the file app/Blog.php and Edit it and inside the class add following method:

 public function createBlog($data)
{

$this->user_id = auth()->user()->id;
$this->title = $data['title'];
$this->description = $data['description'];
$this->category = $data['category'];
$this->save();
return 1;
}


Now the creation of blog task has been done , Its time to show the created Entries So just create a route blog/index in routes/web.php

Route::get('blog/index','BlogController@showAllBlogs');


get route blog/index to show all the created blogs by current user


Now just add a method in controller
public function showAllBlogs()
{
$blogs = Blog::where('user_id', auth()->user()->id)->get();

return view('blog.index',compact('blogs'));
}



This method requires to create a index view in blog folder , So create a file named index.blade.php in /resources/views/blog/ folder with following code

@extends('layouts.app')

@section('content')
<div class="container">
@if(\Session::has('success'))
<div class="alert alert-success">
{{\Session::get('success')}}
</div>
@endif
<a type="button" href="{{url('blog/create')}}" class="btn btn-primary">Add New Blog</a>
<br>
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Title</td>
<td>Category</td>
<td>Description</td>
<td colspan="2">Action</td>
</tr>
</thead>
<tbody>
@foreach($blogs as $blog)
<tr>
<td>{{$blog->id}}</td>
<td>{{$blog->title}}</td>
<td>{{$blog->category}}</td>
<td>{{$blog->description}}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
@endforeach
</tbody>
</table>
<div>
@endsection



Now all code is ready but we need to add 1 line of code to prevent the blog controller without authentication or without login

just add the following constructor method in BlogController class

 public function __construct()
{
$this->middleware('auth');
}


this constructor method will call very first when user will try to access any of BlogController class method, and the middleware will check whether user is logged in then only it will allow to access that method otherwise it will redirect to login page automatically.


After It Run your Code and you will able to create and listing your created blogs/articles. but the Edit and Delete links are not working right now, If you want that also working then please comment here or message me. If we get multiple requests then definitely i will write its part 2 article


Thanks very much for reading this blog, if you have any doubt about it then let me know in comments or by messaging me.

Following is the final code for BlogController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Blog;



class BlogController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}

public function createBlog()
{
return view('blog/create');
}


public function saveBlog(Request $request)
{
$blog = new Blog();

$this->validate($request, [
'title'=>'required',
'category'=>'required',
'description'=> 'required'
]);

$blog->createBlog($request->all());
return redirect('blog/index')->with('success', 'New blog has been created successfully :)');
}

public function showAllBlogs()
{
$blogs = Blog::where('user_id', auth()->user()->id)->get();

return view('blog.index',compact('blogs'));
}

}

20490 views · 5 years ago
Making Charts and Graphs using Laravel

Installing composer

Composer is a package management tool for PHP. Laravel requires composer for installation. We can download composer from https://getcomposer.org/download/

After installation that you can test whether composer installed or not by command
composer

Installing Laravel

The current stable version of laravel is laravel 5.6. We can install laravel package with three ways.

In command prompt or terminal by running composer global require "laravel/installer" and then Laravel new

or

We can create the project with Composer by running composer create-project --prefer-dist laravel/laravel

or

Directly clone from github
git clone https://github.com/laravel/laravel/tree/master and after that composer update

Laravel local development server

Run the below command in command prompt or terminal
PHP artisan serve


Above command will start to local development servehttp://localhost:8000 or if you want to change default port:

php artisan serve --port 


Generating charts and graphs

We are using consoletvs package for generating charts. So for installation we can first move inside to our project using command prompt or terminal. We are following the below steps to install

Step 1:

First we need to install ConsoleTVs/Charts composer package inside our laravel project.
composer require consoletvs/charts


Step 2:

After successfully installation of above package, open app/config.php and add service provider.
In config/app.php


'providers' => [
....
ConsoleTVs\Charts\ChartsServiceProvider::class,
],


After the service provider we need to add alias
'aliases' => [
....
'Charts' => ConsoleTVs\Charts\Facades\Charts::class,
]



Step 3

We need to configure of database for application. We can configure in either .env file or config/database.php file.


Step 4

We can migrate our default tables that is user. We can find the table in database/migration folder.

Step 5

We can generate dummy records for demo in users table. For creating dummy records, we need to run the below command in command prompt or terminal
php artisan tinker>>> factory(App\User::class, 20)->create();

the above command will create a set of 20 records.

If we need to add more records we need to run the above command or we can increase the count as much as we want. For example
php artisan tinker>>> factory(App\User::class, 2000)->create();


Step 6Creating controller

For creating controller we need to run below command in terminal or command prompt
php artisan make controller:<controller_name>


Step 7Adding the routes

We can add the routes for navigating our application. You can find routes file inside routes folder. Before 5.4 we can find routes.php file itself, now its web.php. If you are using laravel 5.2 routes.php will inside app/http folder.

So inside web.php:

Route::get('create-chart/{type}','ChartController@makeChart');


Here type will be the parameter we are passing and it will focus to makeChart() function inside chartcontroller

Step 8

Import charts to controller, for that in the namespace section add:

Use charts;


Step 9

We can put the below code into chartController

public function makeChart($type)
{
switch ($type) {
case 'bar':
$users = User::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"),date('Y'))
->get();
$chart = Charts::database($users, 'bar', 'highcharts')
->title("Monthly new Register Users")
->elementLabel("Total Users")
->dimensions(1000, 500)
->responsive(true)
->groupByMonth(date('Y'), true);
break;
case 'pie':
$chart = Charts::create('pie', 'highcharts')
->title('HDTuto.com Laravel Pie Chart')
->labels(['Codeigniter', 'Laravel', 'PHP'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'donut':
$chart = Charts::create('donut', 'highcharts')
->title('HDTuto.com Laravel Donut Chart')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'line':
$chart = Charts::create('line', 'highcharts')
->title('HDTuto.com Laravel Line Chart')
->elementLabel('HDTuto.com Laravel Line Chart Lable')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'area':
$chart = Charts::create('area', 'highcharts')
->title('HDTuto.com Laravel Area Chart')
->elementLabel('HDTuto.com Laravel Line Chart label')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'geo':
$chart = Charts::create('geo', 'highcharts')
->title('HDTuto.com Laravel GEO Chart')
->elementLabel('HDTuto.com Laravel GEO Chart label')
->labels(['ES', 'FR', 'RU'])
->colors(['#3D3D3D', '#985689'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
default:
break;
}
return view('chart', compact('chart'));
}


Step 10

Create a blade file. Blade is the view file used inside the laravel. You can add new blade file with any name with an extension of .blade.php
Here we are creating chart.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Charts</title>
{!! Charts::styles() !!}
</head>
<body>

<div class="app">
<center>
{!! $chart->html() !!}
</center>
</div>

{!! Charts::scripts() !!}
{!! $chart->script() !!}
</body>
</html>


Step 11

We can run our laravel application in local development server by php artisan serve command:

http://localhost:8000/create-chart/bar
http://localhost:8000/create-chart/pie
http://localhost:8000/create-chart/donut
http://localhost:8000/create-chart/line
http://localhost:8000/create-chart/area
http://localhost:8000/create-chart/geo



In the above example we was creating line chart, geo chart, bar chart, pie chart, donut chart, line chart and area chart. We can also create gauge chart, progressbar chart, areaspline chart, scatter chart, percentage chart etc using consoletvs charts composer package.

There are a lot of jQuery libraries also available like amcharts, chartjs, highcharts, google, material, chartist, fusioncharts, morris, plottablejs etc. However, using this plugin we can easily create charts without having to use jQuery, another advantage to building it in with Laravel.
18923 views · 5 years ago
Install Composer for PHP

Composer is a must-have tool for every PHP developer these days. This page is a simple breakdown of quick-install instructions.

How do I install composer?
   

. Use PHP to download the composer installer, place it in the current directory, and name it composer-setup.php


    . Use PHP to check the hash of the file you downloaded and compare it to the known value of the hash. You can always find the current value of the hash for the installer on the Composer Public Keys / Signatures page.
   
. Run the setup program to install composer. This does more than just download the latest copy of composer, it also sets up your local ~/.composer directory. This will install composer into the current directory. You can add the --install-dir=DIR to specify where you want composer installed. You can also specify --filename=composer to change the installed filename. You can use anything you like that doesn’t already exist in your specified directory, you don’t have to use the name composer. This is a great way to get rid of the .phar at the end of the name if you don’t like it.
   
. Use PHP to remove the installer from the current directory.

To install composer for PHP you use PHP to download the installer, set a few options, and then actually perform the install.

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

php composer-setup.php

php -r "unlink('composer-setup.php');"


Below is a version you can copy ‘n paste.

Breakdown:

Recommended Setup for Linux and macOS:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

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

php -r "unlink('composer-setup.php');"

WARNING: Line two IS WHERE IT compares the hasH of the installer you just downloaded to a hard-coded value. The value specified in the script is the value for the current version of the installer as of this writing. If it fails, check the Composer Public Keys / Signatures page and get the latest version. Plug it into the script below and try again.

Windows user, change the --installdir= to a directory in your path.

Recommended Setup for Windows

If you are running Microsoft Windows, the instructions above will work for you as long as you use the proper install paths. You can however download ComposerSetup.exe from the Composer Introduction page. Execute this and it will install composer and set your path so that you can run composer from anywhere. You will have to close your terminal window and open a new one after the install for the path to be updated.

That’s it, you should now have Composer installed.

Composer installation Resources

* Composer Homepage
* Composer Introduction
* Download Composer
* Composer Public Keys / Signatures
19214 views · 5 years ago
How to install PHPUnit

PHPUnit is an essential tool for every PHP developers. It is one of those tools that every PHP developer should have installed in their development environment. The problems most first time PHPUnit developers run into are where to install it and how to install it. This quick guide will walk you through the process and answer both questions.

How do I install PHPUnit

The Easy Way

In your project’s root directory use this command.

composer require --dev phpunit/phpunit ^6.0


This command adds PHPUnit to your project as a development dependency. This is the absolute best way to install PHPUnit. It is the best way because this way the version of PHPUnit does not change unless you change it. We specified ^6.0 as the version which means we’ll get all the updates to the 6.0 branch but not 6.1. While BC breaks don’t happen often in PHPUnit, they have happened. If you have a globally installed version of PHPUnit and you upgrade it to a version that breaks BC, you have to go update all of your tests immediately. This is a lot of hassle if you have a lot of projects with a lot of tests. Keeping a copy of PHPUnit installed as a dev requirement in each project means that each project has its own copy that can be upgraded as necessary.

The Hard Way

In a command prompt regardless of where you are in your file system, use this command.

composer global require phpunit/phpunit ^6.0


On MacOS and Linux machines, this will install PHPUnit in ~/.composer/vendor/bin. If you add this directory to your path, then from any project, you can execute PHPUnit. However, as noted above, if you ever upgrade your globally installed packages then you will have problems.

composer global update


Run that when there is a new version of PHPUnit, it will be installed, regardless of whether this will break your existing unit tests on one or more of your projects. Windows users will need to locate the .composer/vendor/bin directory in your user’s home directory.

The “ZOMG why would you do it this way” Way

Here is the old-school use wget and move it into the correct position manually. You can do it this way, but you will have to take care of all upgrades manually as well. If you only have a single project on the computer and you never ever plan on changing the version of PHPUnit….nope, still better to usecomposer require --dev.

wget https://phar.phpunit.de/phpunit-6.0.phar


chmod +x phpunit-6.0.phar


sudo mv phpunit-6.0.phar /usr/local/bin/phpunit


phpunit --version


These instructions are of course for MacOS or Linux. Windows user won’t need to do chmod or sudo but will need a BAT file.

That’s it. One of those commands should get you a working copy of PHPUnit on your computer.

Resources:

* Installing PHPUnit
* Composer Introduction (For the Global option)
11883 views · 5 years ago
Five Composer Tips Every PHP Developer Should Know

Composer is the way that that PHP developers manage libraries and their dependencies. Previously, developers mainly stuck to existing frameworks. If you were a Symfony developer, you used Symfony and libraries built around it. You didn’t dare cross the line to Zend Framework. These days however, developers focus less on frameworks, and more on the libraries they need to build the project they are working on. This decoupling of projects from frameworks is largely possible because of Composer and the ecosystem that has built up around it.

Like PHP, Composer is easy to get started in, but complex enough to take time and practice to master. The Composer manual does a great job of getting you up and running quickly, but some of the commands are involved enough so that many developers miss some of their power because they simply don’t understand.

I’ve picked out five commands that every user of Composer should master. In each section I give you a little insight into the command, how it is used, when it is used and why this one is important.

1: Require

Sample:

$ composer require monolog/monolog


Require is the most common command that most developers will use when using Composer. In addition to the vendor/package, you can also specify a version number to load along with modifiers. For instance, if you want version 1.18.0 of monolog specifically and never want the update command to update this, you would use this command.

$ composer require monolog/monolog:1.18.0


This command will not grab the current version of monolog (currently 1.18.2) but will instead install the specific version 1.18.0.

If you always want the most recent version of monolog greater than 1.8.0 you can use the > modifier as shown in this command.

$ composer require monolog/monolog:>1.18.0


If you want the latest in patch in your current version but don’t want any minor updates that may introduce new features, you can specify that using the tilde.

$ composer require monolog/monolog:~1.18.0


The command above will install the latest version of monolog v1.18. Updates will never update beyond the latest 1.18 version.

If you want to stay current on your major version but never want to go above it you can indicate that with the caret.

$ composer require monolog/monolog:^1.18.0


The command above will install the latest version of monolog 1. Updates continue to update beyond 1.18, but will never update to version 2.

There are other options and flags for require, you can find the complete documentation of the command here.

2: Install a package globally

The most common use of Composer is to install and manage a library within a given project. There are however, times when you want to install a given library globally so that all of your projects can use it without you having to specifically require it in each project. Composer is up to the challenge with a modifier to the require command we discussed above, global. The most common use of this is when you are using Composer to manage packages like PHPUnit.

$ composer global require "phpunit/phpunit:^5.3.*"


The command above would install PHPUnit globally. It would also allow it to be updated throughout the 5.0.0 version because we specified ~5.3.* as the version number. You should be careful in installing packages globally. As long as you do not need different versions for different projects you are ok. However, should you start a project and want to use PHPUnit 6.0.0 (when it releases) but PHPUnit 6 breaks backwards compatibility with the PHPUnit 5.* version, you would have trouble. Either you would have to stay with PHPUnit 5 for your new project, or you would have to test all your projects to make sure that your Unit Tests work after upgrading to PHPUnit 6.

Globally installed projects are something to be thought through carefully. When in doubt, install the project locally.

3: Update a single library with Composer

One of the great powers of Composer is that developers can now easily keep their dependencies up-to-date. Not only that, as we discussed in tip #1, each developer can define exactly what “up-to-date” means for them. With this simple command, Composer will check all of your dependencies in a project and download/install the latest applicable versions.

$ composer update


What about those times when you know that a new version of a specific package has released and you want it, but nothing else updated. Composer has you covered here too.

$ composer update monolog/monolog


This command will ignore everything else, and only update the monolog package and it’s dependencies.

It’s great that you can update everything, but there are times when you know that updating one or more of your packages is going to break things in a way that you aren’t ready to deal with. Composer allows you the freedom to cherry-pick the packages that you want to update, and leave the rest for a later time.

4: Don’t install dev dependencies

In a lot of projects I am working on, I want to make sure that the libraries I download and install are working before I start working with them. To this end, many packages will include things like Unit Tests and documentation. This way I can run the unit Tests on my own to validate the package first. This is all fine and good, except when I don’t want them. There are times when I know the package well enough, or have used it enough, to not have to bother with any of that.

Many packages create a distribution package that does not contain tests or docs. (The League of Extraordinary Packages does this by default on all their packages.) If you specify the --prefer-dist flag, Composer will look for a distribution file and use it instead of pulling directly from github. Of course if you want want to make sure you get the full source and all the artifacts, you can use the --prefer-src flag.

5: Optimize your autoload

Regardless of whether you --prefer-dist or --prefer-source, when your package is incorporated into your project with require, it just adds it to the end of your autoloader. This isn’t always the best solution. Therefore Composer gives us the option to optimize the autoloader with the --optimize switch. Optimizing your autoloader converts your entire autoloader into classmaps. Instead of the autoloader having to use file_exists() to locate a file, Composer creates an array of file locations for each class. This can speed up your application by as much as 30%.

$ composer dump-autoload --optimize


The command above can be issued at any time to optimize your autoloader. It’s a good idea to execute this before moving your application into production.

$ composer require monolog/monolog:~1.18.0 -o


You can also use the optimize flag with the require command. Doing this every time you require a new package will keep your autoloader up-to-date. That having said, it’s still a good idea to get in the habit of using the first command as a safety net when you roll to production, just to make sure.

BONUS: Commit your composer.lock

After you have installed your first package with composer, you now have two files in the root of your project, composer.json and composer.lock. Of the two, composer.lock is the most important one. It contains detailed information about every package and version installed. When you issue a composer install in a directory with a composer.lock file, composer will install the exact same packages and versions. Therefore, by pulling a git repo on a production server will replicate the exact same packages in production that were installed in development. Of course the corollary of this is that you never want to commit your vendor/ directory. Since you can recreate it exactly, there is no need to store all of that code in your repo.

It is recommended that also commit your composer.json. When you check out your repo into production and do an install, composer will use the composer.lock instead of the composer.json when present. This means that your production environment is setup exactly like your development environment.

SPONSORS