emGee Software Solutions Custom Database Applications

Share this

Web Design

Best Content Scheduling Tools For WordPress Sites

Managing an editorial calendar is no easy task. But for larger projects this is a must because it’s easy to get confused about which topics you’ve covered and what...

The post Best Content Scheduling Tools For WordPress Sites appeared first on Onextrapixel.

Categories: Web Design

Do Chatbots Help or Hurt Homepage SEO?

Webitect - Sun, 10/15/2017 - 20:42

Looking for ways to improve your homepage SEO? Thinking about an adding a chatbot to your website? If you’ve been online at all in the past few years, you’ve likely encountered a chatbot popping up on your screen when visiting an e-commerce store or other business, asking you if you would like assistance. Chatbots are the way of the future. Chatbots have many features and benefits that can really be a big help for a business. However, although chatbots can be great for marketing and customer service, they can also come with a lot of limitations. You may be wondering

The post Do Chatbots Help or Hurt Homepage SEO? appeared first on Webitect.

Categories: Web Design

How to Monetize Food Blogs with SEO Tips

Webitect - Sat, 10/14/2017 - 20:38

Did you know monetizing your food blog doesn’t have to be difficult? There are some simple techniques you can use to maximize the return on your investment in your blogs. Let’s take a look at a few SEO tips on how you can best monetize food blogs. Why Is Monetizing My Food Blogs Important? Money is only a symbol. It’s useless paper until we add value to it. But that value we place on it is important. And this symbol signifies many important milestones for your blog, including: Reinforcement for your effort, time and the quality of your content Support

The post How to Monetize Food Blogs with SEO Tips appeared first on Webitect.

Categories: Web Design

Monthly Web Development Update 10/2017: CSS Grid, CAA Pitfalls, And Image Optimization

Smashing Magazine - Fri, 10/13/2017 - 10:56
Editor’s Note: Welcome to this month’s web development update. Anselm has summarized the most important happenings in the web community that have taken place over the past few weeks in one handy list for you. Enjoy! As web developers, we’re working in a very diverse environment: We have countless options to specialize in, but it’s impossible to keep up with everything. This week I read an article from a developer who realized that even though he has been building stuff for the web for over seven years, sometimes he just doesn’t understand what’s going on: “I’m slamming my keyboard in frustration as another mysterious error appears in my build script,” he writes.
Categories: Web Design

Best Affiliate WooCommerce Plugins Compared

Tuts+ Code - Web Development - Fri, 10/13/2017 - 05:00

WooCommerce and WordPress have become a powerful combination for online commerce. Leveraging these two is the perfect combination for selling physical products, digital goods, and services online. It's certainly no accident that it has become "the most customizable eCommerce platform for building your online business."

But having the most awesome WooCommerce storefront and the best products may not be all you need to find online business success. You may want to consider an affiliate program to help spread the word and get your business in front of as many eyes as you can.

Let's take a quick look at some of the best affiliate WooCommerce plugins and how they compare.

Affiliate WooCommerce Plugins You're Looking For

The following affiliate WooCommerce plugins are what you would usually find in an affiliate solution. There is some deviation among these, but nothing too extreme. You'll find differences in their feature sets and approaches. From simple to robust, to earning points to multilevel referrals, these are the affiliate WooCommerce plugins you were probably looking for.

Ultimate Affiliate Pro WordPress Plugin

Let's start with the Ultimate Affiliate Pro WordPress Plugin.

It is easily one of the most robust affiliate WooCommerce plugins as it is integrated with WooCommerce, Easy Digital Downloads, PayPal, and Stripe, and it includes a robust feature set to get your own affiliate program up and running.

You'll find all sorts of useful features such as:

  • performance bonuses and banner management
  • unlimited affiliates and special offers
  • rankings and commission levels
  • referrals and social shares
  • PayPal and Stripe Payouts
  • and much, much more

This is one of the best affiliate WooCommerce plugins you'll find on Envato Market.

If this all wasn't impressive enough, this also includes free login, register, and account page templates; and connects with the top email marketing platforms like MailChimp, Constant Contact, and many more.

Ultimate Affiliate Pro WordPress Plugin is the ultimate affiliate WordPress plugin.

WooCommerce-Probox

If you're looking for something a little more WooCommerce centric that offers a unique approach to affiliates, here's a WordPress plugin you'll want to check out.

"Your users and visitors can customize the look of the products’ widget to place it into their own web sites and pages by simply copying a line of code into their web pages."

So instead of providing an affiliate link, you can make a widget generator for users to create custom snippets to be placed and embedded into their website for referrals.

Features include:

  • place your widget generator with a simple shortcode
  • add to cart button widget option
  • visual widget options
  • and more

The Woocommerce-Probox takes a clever approach, taking your affiliate program beyond the affiliate link.

WooCommerce Multilevel Referral Plugin

Interested in building a strong referral chain?

The WooCommerce Multilevel Referral Plugin allows affiliates to earn credit points while their followers purchase your products from the existing online store.

Build your affiliate perks through sales.

Features you'll find here:

  • set custom credit and redemption limits
  • full admin reporting of registered users
  • global or product specific settings
  • shortcode support
  • and much more

This is a multilevel referral system for WooCommerce, something that's outside of the typical affiliate transactional system.

WooCommerce Multilevel Referral Plugin is unique in approach and may be exactly what you're looking for.

SUMO Affiliates - WooCommerce Affiliate System

The SUMO Affiliates - WooCommerce Affiliate System is simple and straightforward.

Its approach is on point:

"...logged in users can apply and become Affiliates and promote the products in the site. Whenever a user purchases a product by using an Affiliate Link, the Affiliate associated with the link will earn commission for the purchase."

This solid solution works with WooCommerce supported themes and also includes:

  • CSV export for unpaid commissions
  • translation and WPML ready
  • affiliate cookie validator
  • affiliate link generator
  • highly customizable
  • affiliate applications
  • affiliate dashboard
  • and much more

If you're just looking for an affiliate WooCommerce plugin, look no further.

The SUMO Affiliates - WooCommerce Affiliate System hits all the right marks.

Add Some Amazon?

WooCommerce is an excellent platform for selling digital and physical products with WordPress. Adding an affiliate system is an excellent way to increase your reach around the web and reward those who are funneling more sales your way.

But what if you sold your own products and became an affiliate yourself?

RelaZone - Related Amazon Products

By using the RelaZone - Related Amazon Products affiliate WooCommerce plugin, you can advertise Amazon related products with your WooCommerce products.

This solution can be used on any WordPress site, blogs included, but this solution could be a great way to augment your own products.

Features include:

  • post, page, store product display options
  • six front-end templates included
  • Amazon Affiliate compatible
  • link products to keywords
  • 90-day cookies
  • and more

Get some Amazon affiliate traffic on your WordPress site with RelaZone - Related Amazon Products.

Going Fully Affiliate

I've always thought of WooCommerce as being a physical and digital marketplace for those creating a product or offering a service.

But that's not what it is limited to. It can also be used for affiliates.

Let's face it, Amazon and other marketplaces are full of everything. So what if you offered a niche of particular products? A curation of the tidal wave that comes your way with every product search?

By using the power of WordPress, WooCommerce, and some of the following plugins, you can create a niche portal that has the look, feel, and convenience of a WooCommerce shopping experience, while serving users products from Amazon, Walmart, and others.

WooAffiliates - WordPress Plugin

Of all the affiliate WooCommerce WordPress plugins, this is the most robust of the bunch.

WooAffiliates - WordPress Plugin draws from some of the biggest online names, including Amazon, eBay, and our very own Envato Market.

Earn commissions from all, some, or simply one. Features include:

  • easy product import
  • advance search
  • geotargeting
  • bulk import
  • and more

Join the biggest affiliate networks and then get started with the WooAffiliates - WordPress Plugin.

WordPress Monetize Now

You're using Envato right now. You've searched and found your favorites, so why not build out your own affiliate site?

You'll want to use WordPress Monetize Now.

"It also connects to your Envato account and right in your WordPress admin you’ll have all the statistics of your account and the last statement."

Features include:

  • for both Envato authors and non-authors
  • all-in-one shortcode generator
  • official Envato API v3
  • real-time stats
  • and more

WordPress Monetize Now will help you monetize now!

WPCJ Pro - WooCommerce CJ Affiliate WordPress Plugin

WPCJ Pro - WooCommerce CJ Affiliate WordPress Plugin will convert your WooCommerce store into an affiliate website by CJ.com.

Some features include:

  • cron job scheduling
  • automatic import
  • import options
  • and more

Are you a CJ affiliate?

WPCJ Pro - WooCommerce CJ Affiliate WordPress Plugin is your best bet.

Walmart to WooCommerce Affiliate

Just behind Amazon, you've got another big player in the online commerce and affiliate game: Walmart.

Wire up your affiliate WooCommerce store with the easy to use Walmart to WooCommerce Affiliate plugin.

"Earn Commission by redirecting to Walmart from your WooCommerce site using Walmart affiliate link share id."

Import products from Walmart into your WooCommerce site based on keyword search.

It's that simple.

If you're interested in building your own Walmart affiliate store, Walmart to WooCommerce Affiliate is exactly what you want.

WooCommerce eBay Product Import Manager

WooCommerce eBay Product Import Manager sets up your affiliate site using the eBay Affiliate with eBay Partner Network.

Import products with

  • item and category URLs
  • store and seller name
  • keyboard
  • IDs
  • and more

Start earning commission as an eBay affiliate with WooCommerce eBay Product Import Manager.

Conclusion

Offering an affiliate program for your products and services is an excellent way to leverage grassroots advertisers and help identify where you may want to give more attention. Envato Market offers some solid and unique solutions that are worth serious consideration.

Diving into this comparison of the different affiliate WooCommerce plugins, I was surprised to find affiliate WooCommerce plugins that were built with affiliates in mind. It was honestly something I had never thought of before.

If you're looking to start your own affiliate program or you're an affiliate yourself, you're likely to find the best affiliate WooCommerce plugin here.

Categories: Web Design

Monthly Web Development Update 10/2017: CSS Grid, CAA Pitfalls, And Image Optimization

Smashing Magazine - Fri, 10/13/2017 - 02:56

   

Editor’s Note: Welcome to this month’s web development update. Anselm has summarized the most important happenings in the web community that have taken place over the past few weeks in one handy list for you. Enjoy!

As web developers, we’re working in a very diverse environment: We have countless options to specialize in, but it’s impossible to keep up with everything. This week I read an article from a developer who realized that even though he has been building stuff for the web for over seven years, sometimes he just doesn’t understand what’s going on: “I’m slamming my keyboard in frustration as another mysterious error appears in my build script,” he writes.

The post Monthly Web Development Update 10/2017: CSS Grid, CAA Pitfalls, And Image Optimization appeared first on Smashing Magazine.

Categories: Web Design

Don’t Let Your Brain Deceive You: Avoiding Bias In Your UX Feedback

Smashing Magazine - Thu, 10/12/2017 - 13:34
You know that user feedback is crucial — after all, your users will decide whether your app succeeds or not — but how do you know whether users are being fair and objective in their feedback? We can tell you: They won’t be. All of your users will be giving you biased feedback. They can’t help it. When soliciting and listening to user feedback, you will inevitably run into bias on both sides of the coin: Biases will influence the people providing feedback, and your own biases will influence the way you receive that feedback.
Categories: Web Design

Don’t Let Your Brain Deceive You: Avoiding Bias In Your UX Feedback

Smashing Magazine - Thu, 10/12/2017 - 05:34

   

You know that user feedback is crucial — after all, your users will decide whether your app succeeds or not — but how do you know whether users are being fair and objective in their feedback?

We can tell you: They won’t be. All of your users will be giving you biased feedback. They can’t help it.

The post Don’t Let Your Brain Deceive You: Avoiding Bias In Your UX Feedback appeared first on Smashing Magazine.

Categories: Web Design

Vue.js Crash Course: Create a Simple Blog Using Vue.js

Tuts+ Code - Web Development - Thu, 10/12/2017 - 05:00

Vue is a progressive JavaScript framework that focuses on building user interfaces. It focuses heavily on the ViewModel. To learn more, go over to the documentation to see things for yourself.

In this tutorial, you will get your hands dirty with Vue.js by building a simple blog. The blog will have a form that allows you create a post. However, the post that will be displayed on the blog will be retrieved from a resource available online. 

Sounds like fun? Let us get busy.

Getting Started

Start by running the command:

vue init webpack blogapp

Now migrate into the newly created folder and run the command to install your modules.

npm install

This will install all the modules listed in your package.json.

Now start up your dev server to see what you have. Simply run the command below.

npm run devInput Binding

First, create a new file called addBlog.vue in your src/components folder. This file you are creating is called a component.

Components are used to extend basic HTML elements to encapsulate reusable code. This component will handle the creation of new blog post. Here is how the file should look.

#src/components/addBlog.vue <template> <div id="add-blog"> <h2>Add a New Blog Post</h2> <form v-if="!submitted"> <label>Blog Title:</label> <input type="text" v-model.lazy="blog.title" required /> <label>Blog Content:</label> <textarea v-model.lazy.trim="blog.content"></textarea> <div id="checkboxes"> <p>Blog Categories:</p> <label>Ninjas</label> <input type="checkbox" value="ninjas" v-model="blog.categories" /> <label>Wizards</label> <input type="checkbox" value="wizards" v-model="blog.categories" /> <label>Mario</label> <input type="checkbox" value="mario" v-model="blog.categories" /> <label>Cheese</label> <input type="checkbox" value="cheese" v-model="blog.categories" /> </div> <label>Author:</label> <select v-model="blog.author"> <option v-for="author in authors">{{ author }}</option> </select> <button v-on:click.prevent="addPost">Add Blog</button> </form> <div v-if="submitted"> <h3>Thanks for adding your post</h3> </div> <div id="preview"> <h3>Preview blog</h3> <p>Blog title: {{ blog.title }}</p> <p>Blog content:</p> <p style="white-space: pre">{{ blog.content }}</p> <p>Blog Categories:</p> <ul> <li v-for="category in blog.categories">{{ category }}</li> </ul> <p>Author: {{ blog.author }}</p> </div> </div> </template> <script> // Imports export default { data () { return { blog: { title: '', content: '', categories: [], author: '' }, authors: ['The Net Ninja', 'The Angular Avenger', 'The Vue Vindicator'], submitted: false } }, methods: { } } </script> <style> #add-blog *{ box-sizing: border-box; } #add-blog{ margin: 20px auto; max-width: 500px; } label{ display: block; margin: 20px 0 10px; } input[type="text"], textarea{ display: block; width: 100%; padding: 8px; } #preview{ padding: 10px 20px; border: 1px dotted #ccc; margin: 30px 0; } h3{ margin-top: 10px; } #checkboxes input{ display: inline-block; margin-right: 10px; } #checkboxes label{ display: inline-block; margin-top: 0; } </style>

In the template section, you have two parts. The first is a form to create a new post, and the other gives a preview of what is entered in the form. With this, you can see the inputs you enter before saving the post. This is possible using a v-model, which is a directive that allows us to perform two-way data bindings on form inputs. It automatically updates the DOM based on the input entered. The data binding is also possible for select options and checkboxes, as you can see above.

A directive is a special token in the markup that tells the library to do something to a DOM element.

For instance, the line of code <input type="text" v-model.lazy="blog.title" required /> will bind the value entered into the field to be the value of blog.title. This value according to what you have above is outputted where you have <p>Blog title: {{ blog.title }}</p>.

v-for is used to loop through a collection. In the above, you use v-for to loop through a collection of authors and categories.

It is possible to make use of conditionals in Vue. You see that play out when you set the default value of submitted to false. The line <form v-if="!submitted"> tells Vue to display the form if the value of submitted is false. After making a post, it is important to change this to true, and this will be done in the function that gets called for the creation of new posts. After this happens, the form disappears, and the preview of your post with a div that contains an appreciation message is shown.

In the script section, you create a blog object with some properties. These properties store the values entered in our form. The data binding will not be possible without the registration of the properties in our Vue instance.

HTTP Request

Your blog needs to have a database where posts will be saved, but that is outside the scope of this tutorial. You will learn how to work with Vue.js and Firebase in an upcoming tutorial. For this, you will make use of a service that allows you to make HTTP GET and POST requests, and the service is called JSONPlaceholder. You will see how we use it in this post shortly.

There are different ways to make an HTTP request in Vue.js. One way is to use vue-resource, and this is what you will use for this tutorial.

To install it, run the command below:

npm install vue-resource --save

You will need to import vue-resource and tell Vue that you want to make use of it. To do that, open src/main.js and drop in the code below.

#src/main.js ... import VueResource from 'vue-resource' Vue.use(VueResource) ...

Now you need to implement the function you added to the button of the form. This function will be used to create the new post. In the script section, add the block of code inside the method block.

#src/components/addBlog.vue ... methods: { addPost: function () { this.$http.post('http://jsonplaceholder.typicode.com/posts', { title: this.blog.title, body: this.blog.content, userId: 1 }).then(function(data){ console.log(data) this.submitted = true }) } } ...

Here you are making a POST request to http://jsonplaceholder.typicode.com/posts, and you pass an object that contains the values of the new post you are about to create. The value of submitted is set to true. When the button to add a new post is clicked, the page is automatically updated to show your appreciation message and the preview of the post.

Create the Second Component

In your blog, you will possibly want to have a page that lists all the posts available on your blog. Just the title of each post will do.

To do this, you will need to create a new component in the same directory where you created the component that enables you to create a new post. Here is how it should look.

#src/components/showBlog.vue <template> <div id="show-blogs"> <h1>All Blog Posts</h1> <div v-for="blog in blogs" class="single-blog"> <h2>{{ blog.title }}</h2> <article>{{ blog.content }}</article> </div> </div> </template> <script> export default { data () { return { blogs: [] } }, methods: { }, created () { this.$http.get('http://jsonplaceholder.typicode.com/posts').then((data) => { this.blogs = data.body.slice(0, 10) }) } } </script> <style> #show-blogs{ max-width: 800px; margin: 0px auto; } .single-blog{ padding: 20px; margin: 20px 0; box-sizing: border-box; background: #eee; } </style>

In the above, you loop through your blog collection and display the title and content of each article.

In the script section, you are sending an HTTP GET request to the resource specified. The posts are returned and set as blogs. However you do not want to display all posts on your page, so splice is used to show just 10 posts.

Hook Up the Routes

Now you can set up your routes. Create a header component; this component will house your navigation links.

#src/components/header.vue <template> <nav> <ul> <li><router-link to="/">Blog</router-link></li> <li><router-link to="/add">Add new post</router-link></li> </ul> </nav> </template> <script> export default { } </script> <style scoped> ul{ list-style-type: none; text-align: center; margin: 0; } li{ display: inline-block; margin: 0 10px; } a{ color: #fff; text-decoration: none; padding: 6px 8px; border-radius: 10px; } nav{ background: #444; padding: 14px 0; margin-bottom: 40px; } .router-link-active{ background: #eee; color: #444; } </style>

This does not do much; it simply holds your link and makes use of VueRouter. For the links to work, you need to add them to your routes file, like this.

#src/router/index.js import Vue from 'vue' import Router from 'vue-router' import addBlog from '../components/addBlog' import showBlogs from '../components/showBlogs' Vue.use(Router) export default new Router({ routes: [ { path: '/add', component: addBlog }, { path: '/', component: showBlogs } ] })

Here you simply import your components and set the path with which they can be accessed.

Having done all that, clean up your App component to look like this.

#src/components/App.vue <template> <div id="app"> <app-header></app-header> <router-view></router-view> </div> </template> <script> import header from './components/header' export default { components: { 'app-header': header } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>

You are only importing the header component you just created, and outputting it in your template. In order to display a component, you must register it, and this is what you do in the component block of your script section.

Now your blog is all good for testing, so start up your dev server.

npm run devConclusion

This is just a crash course to try your hand at Vue.js. You got your hands dirty by creating custom components. You made use of vue-resource to send HTTP requests. With the new knowledge, you can go ahead and try to build something simple like a note application with preview capabilities.

JavaScript has become one of the de facto languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

In future tutorials, we will dive deep into the various parts of Vue.js. See you some other time.

Categories: Web Design

19 Experts Explain Why Your Website Isn't Bringing in Customers

Entrepreneur: Latest Web Design Articles - Thu, 10/12/2017 - 05:00
There's no shortage of reasons your pages aren't finding their target markets or inspiring visitors to convert.
Categories: Web Design

Implementing A Service Worker For Single-Page App WordPress Sites

Smashing Magazine - Wed, 10/11/2017 - 14:47
With so many JavaScript frameworks around, single-page application (SPA) websites seem to be all the rage nowadays. However, an SPA architecture has the drawback of having a slower first-page load than a server-based application, because all of the JavaScript templates used to render the HTML view must be downloaded before the required view can be generated. Enter service workers. Through service workers, all framework and application code to output the HTML view can be precached in the browser, thus speeding up both the first meaningful paint and the time to interact.
Categories: Web Design

Implementing A Service Worker For Single-Page App WordPress Sites

Smashing Magazine - Wed, 10/11/2017 - 06:47

   

With so many JavaScript frameworks around, single-page application (SPA) websites seem to be all the rage nowadays. However, an SPA architecture has the drawback of having a slower first-page load than a server-based application, because all of the JavaScript templates used to render the HTML view must be downloaded before the required view can be generated.

Enter service workers. Through service workers, all framework and application code to output the HTML view can be precached in the browser, thus speeding up both the first meaningful paint and the time to interact. In this article, I will share my experience with implementing service workers for PoP, an SPA website that runs on WordPress, with the goal of speeding up the loading time and providing offline-first capabilities.

The post Implementing A Service Worker For Single-Page App WordPress Sites appeared first on Smashing Magazine.

Categories: Web Design

Build a React App With a Laravel Back End: Part 2, React

Tuts+ Code - Web Development - Wed, 10/11/2017 - 05:00
What You'll Be Creating

This is the second and final part of the series on building a React application with a Laravel back end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be developing the front end using React. 

We will also consider all the available options to bridge the gap between Laravel and React. You don't need to have followed part one of the series to understand this tutorial. If you're here to see how React and Laravel fare together, you can, in fact, avoid the first part. You should head over to GitHub, clone the repo, and take the quick recap down below to get started.

A Quick Recap

In the previous tutorial, we developed a Laravel application that responds to API calls. We created routes, a controller, and a model for the simple product listing application. Since it was the controller's job to return a response to the HTTP requests, the view section was entirely skipped. 

Then we discussed techniques for exception handling and validation using Laravel. By the end of the tutorial, we had a Laravel back-end API. We can now use this API to build applications for both the web and a wide range of mobile devices. 

In this tutorial, we will be shifting our focus towards the front end. The first half of the tutorial is about setting up React in a Laravel environment. I will also introduce you to Laravel Mix (supported by Laravel 5.4 and later), which is an API for compiling assets. In the second half of the tutorial, we will start building a React application from scratch. 

Setting Up React in Laravel

Laravel Mix was introduced in Laravel 5.4, and it is currently the ideal way to hook up React and Laravel. With Laravel 5.5, the whole process was made much easier. I've described both methods below. 

Using the React Preset Command (Laravel 5.5)

Laravel 5.5 has a brand new feature that lets you scaffold the code for React components using artisan's preset react command. In previous versions of Laravel, setting up React inside Laravel wasn't this easy. If you're running the latest version of Laravel, then run the below command to add a React preset to your project. 

php artisan preset react

Laravel by default gets shipped with the Vue preset, and the above command replaces all instances of Vue with React. Interestingly, if you don't need a preset, you can remove them altogether using the php artisan preset none command. 

If everything goes well, this should show up in your terminal.

React scaffolding installed successfully. Please run "npm install && npm run dev" to compile your fresh scaffolding.

In the background, Laravel uses Laravel Mix, which is a smooth wrapper for webpack. Webpack, as you might already know, is a module bundler. It resolves all the module dependencies and generates the necessary static assets for JavaScript and CSS. React requires a module bundler to work, and webpack perfectly fits into that role. So Laravel Mix is the layer that sits on top of webpack and makes it easier to use webpack in Laravel.  

A better understanding of how Laravel Mix works is important if you need to customize the webpack configuration at a later time. The React preset command gives us no information about how things work in the background. So let's remove the React preset and retrace the steps manually instead. 

Manual Method (Laravel 5.4)

If you're running Laravel 5.4, or if you are just curious to see how Laravel Mix is configured, here are the steps that you need to follow:

Install react, react-dom and babel-preset-react using npm. It might be a good idea to have yarn installed too. It's no secret that Laravel and React prefer yarn over npm.

Head over to webpack.mix.js, located inside the root directory of your Laravel project. This is the configuration file where you declare how your assets should be compiled. Replace the line mix.js('resources/assets/js/app.js', 'public/js'); with mix.react('resources/assets/js/app.js', 'public/js');. app.js is the entry point for our JavaScript files, and the compiled files will be located inside public/js. Run npm install in the terminal to install all the dependencies.

Next, go to resources/assets/js. There's already a components folder and a couple of other JavaScript files. React components will go into the components directory. Remove the existing Example.vue file and create a new file for a sample React component.

resources/assets/js/component/Main.jsimport React, { Component } from 'react'; import ReactDOM from 'react-dom'; /* An example React component */ class Main extends Component { render() { return ( <div> <h3>All Products</h3> </div> ); } } export default Main; /* The if statement is required so as to Render the component on pages that have a div with an ID of "root"; */ if (document.getElementById('root')) { ReactDOM.render(<Main />, document.getElementById('root')); }

Update app.js to remove all the Vue-related code and import the React component instead. 

resources/assets/js/app.jsrequire('./bootstrap'); /* Import the Main component */ import Main from './components/Main';

Now, we just need to make the assets accessible to the View. The view files are located inside the resources/views directory. Let's add a <script> tag to welcome.blade.php, which is the default page rendered when you navigate to localhost:8000/. Remove the contents of the view file and replace it with the code below:

 resources/views/welcome.blade.php

<!doctype html> <html lang="{{ app()->getLocale() }}"> <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>Laravel React application</title> <link href="{{mix('css/app.css')}}" rel="stylesheet" type="text/css"> </head> <body> <h2 style="text-align: center"> Laravel and React application </h2> <div id="root"></div> <script src="{{mix('js/app.js')}}" ></script> </body> </html>

Finally, execute npm run dev or yarn run dev to compile the assets. If you visit localhost:8000, you should see:

React embedded inside Laravel's view.

The package.json has a watch script that auto-compiles the assets when any changes are detected. To enable this mode, run npm run watch. 

Congrats, you've successfully configured React to work with Laravel. Now, let's create some React components for the front end. 

Developing the React Application

If you're new to React, you will find the rest of the tutorial somewhat challenging. I recommend taking the React Crash Course for Beginners series to get acquainted with the React concepts better. Let's get started!

A React application is built around components. Components are the most important structure in React, and we have a directory dedicated for components.

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
— Official React Docs

For the application that we are building, we will start with a basic component that displays all the products returned by the server. Let's name it the Main component. The component should take care of the following things initially:

  • Fetch all the products from the API (GET /api/products).
  • Store the product data in its state.
  • Display the product data.

React isn't a full-fledged framework, and hence the library doesn't have any AJAX features on its own. I will be using fetch(), which is a standard JavaScript API for fetching the data from the server. But there are tons of alternatives to make AJAX calls to the server. 

resources/assets/js/component/Main.jsimport React, { Component } from 'react'; import ReactDOM from 'react-dom'; /* Main Component */ class Main extends Component { constructor() { super(); //Initialize the state in the constructor this.state = { products: [], } } /*componentDidMount() is a lifecycle method * that gets called after the component is rendered */ componentDidMount() { /* fetch API in action */ fetch('/api/products') .then(response => { return response.json(); }) .then(products => { //Fetched product is stored in the state this.setState({ products }); }); } renderProducts() { return this.state.products.map(product => { return ( /* When using list you need to specify a key * attribute that is unique for each list item */ <li key={product.id} > { product.title } </li> ); }) } render() { /* Some css code has been removed for brevity */ return ( <div> <ul> { this.renderProducts() } </ul> </div> ); } }

Here we're initializing the state of products to an empty array in the constructor. Once the component mounts, we use fetch() to retrieve the products from /api/products and store it in the state. The render method is used to describe the UI of the component. All the products get rendered as a list there. 

The page just lists the product titles, which is boring. Moreover, we don't have any interactive elements in there yet. Let's make the product title clickable, and on click, more details about the product will get rendered. 

Displaying Product Data

Here's the list of things that we need to cover:

  • A  state to track the product that was clicked. Let's call it currentProduct with an initial null value.
  • When a product title is clicked, this.state.currentProduct is updated.
  • The product details of the concerned product are displayed on the right. Until a product is selected, it displays the "No product selected" message.
resources/assets/js/component/Main.jsimport React, { Component } from 'react'; import ReactDOM from 'react-dom'; /* Main Component */ class Main extends Component { constructor() { super(); /* currentProduct keeps track of the product currently * displayed */ this.state = { products: [], currentProduct: null } } componentDidMount() { //code omitted for brevity } renderProducts() { return this.state.products.map(product => { return ( //this.handleClick() method is invoked onClick. <li onClick={ () =>this.handleClick(product)} key={product.id} > { product.title } </li> ); }) } handleClick(product) { //handleClick is used to set the state this.setState({currentProduct:product}); } render() { /* Some css code has been removed for brevity */ return ( <div> <ul> { this.renderProducts() } </ul> </div> ); } }

Here we've added createProduct into the state and initialized it with the value null. The line onClick={ () =>this.handleClick(product) } invokes the handleClick() method when the list item is clicked. The handleClick() method updates the state of currentProduct. 

Now to display the product data, we can either render it inside the Main component or create a new component. As previously mentioned, splitting the UI into smaller components is the React way of doing things. So we will create a new component and name it Product.

The Product component is nested inside the Main component. The Main component passes its state as props. The Product component accepts this props as input and renders the relevant information.

resources/assets/js/component/Main.jsrender() { return ( /* The extra divs are for the css styles */ <div> <div> <h3> All products </h3> <ul> { this.renderProducts() } </ul> </div> <Product product={this.state.currentProduct} /> </div> ); } }resources/assets/js/component/Product.jsimport React, { Component } from 'react'; /* Stateless component or pure component * { product } syntax is the object destructing */ const Product = ({product}) => { const divStyle = { /*code omitted for brevity */ } //if the props product is null, return Product doesn't exist if(!product) { return(<div style={divStyle}> Product Doesnt exist </div>); } //Else, display the product data return( <div style={divStyle}> <h2> {product.title} </h2> <p> {product.description} </p> <h3> Status {product.availability ? 'Available' : 'Out of stock'} </h3> <h3> Price : {product.price} </h3> </div> ) } export default Product ;

The application should look something like this now:

Adding a New Product

We've successfully implemented the front end corresponding to retrieving all the products and displaying them. Next, we need a form to add a new product to the product list. The process for adding a product might feel a bit more complex than just fetching the data from an API.

Here's what I think is required to develop this feature:

  • A new stateful component that renders the UI for an input form. The component's state holds the form data.
  • On submit, the child component passes the state to the Main component using a callback.
  • The Main component has a method, say handleNewProduct(), that handles the logic for starting a POST request. Upon receiving the response, the Main component updates its state (both this.state.products and this.state.currentProduct) 

That doesn't sound very complex, does it? Let's do it step by step. First, create a new component. I am going to call it AddProduct. 

resources/assets/js/component/AddProduct.jsclass AddProduct extends Component { constructor(props) { super(props); /* Initialize the state. */ this.state = { newProduct: { title: '', description: '', price: 0, availability: 0 } } //Boilerplate code for binding methods with `this` this.handleSubmit = this.handleSubmit.bind(this); this.handleInput = this.handleInput.bind(this); } /* This method dynamically accepts inputs and stores it in the state */ handleInput(key, e) { /*Duplicating and updating the state */ var state = Object.assign({}, this.state.newProduct); state[key] = e.target.value; this.setState({newProduct: state }); } /* This method is invoked when submit button is pressed */ handleSubmit(e) { //preventDefault prevents page reload e.preventDefault(); /*A call back to the onAdd props. The current *state is passed as a param */ this.props.onAdd(this.state.newProduct); } render() { const divStyle = { /*Code omitted for brevity */ } return( <div> <h2> Add new product </h2> <div style={divStyle}> /*when Submit button is pressed, the control is passed to *handleSubmit method */ <form onSubmit={this.handleSubmit}> <label> Title: { /*On every keystroke, the handeInput method is invoked */ } <input type="text" onChange={(e)=>this.handleInput('title',e)} /> </label> <label> Description: <input type="text" onChange={(e)=>this.handleInput('description',e)} /> </label> { /* Input fields for Price and availability omitted for brevity */} <input type="submit" value="Submit" /> </form> </div> </div>) } } export default AddProduct;

The component basically renders an input form, and all the input values are stored in the state (this.state.newProduct). Then, on form submission, handleSubmit() method gets invoked. But AddProduct needs to communicate the information back to the parent, and we do this using a callback. 

The Main component, which is the parent, passes a function reference as props. The child component, AddProduct in our case, invokes this props to notify the parent of the state change. So the line this.props.onAdd(this.state.newProduct); is an example of a callback that notifies the parent component of the new product. 

Now, inside the Main component, we shall declare <AddProduct /> as follows:

<AddProduct onAdd={this.handleAddProduct} />

The onAdd event handler is chained to the component's handleAddProduct() method. This method hosts the code for making a POST request to the server. If the response indicates that the product has been successfully created, the state of products and currentProducts is updated. 

handleAddProduct(product) { product.price = Number(product.price); /*Fetch API for post request */ fetch( 'api/products/', { method:'post', /* headers are important*/ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(product) }) .then(response => { return response.json(); }) .then( data => { //update the state of products and currentProduct this.setState((prevState)=> ({ products: prevState.products.concat(data), currentProduct : data })) }) }

Don't forget to bind the handleProduct method to the class using this.handleAddProduct = this.handleAddProduct.bind(this); in the constructor. And here's the final version of the application:

What Next?

The application is incomplete without the delete and update features. But if you've been following the tutorial closely until now, you should be able to fill in the void without much trouble. To get you started, I've provided you the event handler logic for both the delete and update scenario.

Logic for Deleting a Product handleDelete() { const currentProduct = this.state.currentProduct; fetch( 'api/products/' + this.state.currentProduct.id, { method: 'delete' }) .then(response => { /* Duplicate the array and filter out the item to be deleted */ var array = this.state.products.filter(function(item) { return item !== currentProduct }); this.setState({ products: array, currentProduct: null}); }); }Logic for Updating an Existing ProducthandleUpdate(product) { const currentProduct = this.state.currentProduct; fetch( 'api/products/' + currentProduct.id, { method:'put', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(product) }) .then(response => { return response.json(); }) .then( data => { /* Updating the state */ var array = this.state.products.filter(function(item) { return item !== currentProduct }) this.setState((prevState)=> ({ products: array.concat(product), currentProduct : product })) }) }

What you need to do is dive in, get your hands dirty, and finish the application using the above logic. I will drop you a hint: The delete button should ideally go inside the Product component, whereas the update feature should have a component of its own. I encourage you to take up this challenge and finish the missing components.

Summary

We've come a long way from where we started. First, we created a REST API using the Laravel framework. Then, we discussed our options for mixing Laravel and React. Finally, we built a front end to the API using React. 

Although we primarily focused on creating a single-page application using React, you can create widgets or components that are mounted to specific elements in your views. React is very flexible because it's a library, and a good one.

Over the last couple of year, React has grown in popularity. In fact, we’ve a number of items in the marketplace that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.

Have you tried experimenting with Laravel and React before? What are your thoughts? Share them with us in the comments.

Categories: Web Design

15 Inspiring WordPress Sites

WordPress started out purely as a simple blogging platform. Then it spent the next few years developing into a CMS. And now it is the most used CMS in...

The post 15 Inspiring WordPress Sites appeared first on Onextrapixel.

Categories: Web Design

Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API

Tuts+ Code - Web Development - Tue, 10/10/2017 - 05:00

Laravel and React are two popular web development technologies used for building modern web applications. Laravel is prominently a server-side PHP framework, whereas React is a client-side JavaScript library. This tutorial serves as an introduction to both Laravel and React, combining them to create a modern web application. 

In a modern web application, the server has a limited job of managing the back end through some API (Application Programming Interface) endpoints. The client sends requests to these endpoints, and the server returns a response. However, the server is not concerned about how the client renders the view, which falls perfectly in line with the Separation of Concerns principle. This architecture allows developers to build robust applications for the web and also for different devices. 

In this tutorial, we will be using the latest version of Laravel, version 5.5, to create a RESTful back-end API. The front end will comprise of components written in React. We will be building a resourceful product listing application. The first part of the tutorial will focus more on the Laravel concepts and the back end. Let's get started. 

Introduction

Laravel is a PHP framework developed for the modern web. It has an expressive syntax that favors the convention over configuration paradigm. Laravel has all the features that you need to get started with a project right out of the box. But personally, I like Laravel because it turns development with PHP into an entirely different experience and workflow.  

On the other hand, React is a popular JavaScript library developed by Facebook for building single-page applications. React helps you break down your view into components where each component describes a part of the application's UI. The component-based approach has the added benefit of component reusability and modularity.

Why Laravel and React?

If you're developing for the web, you might be inclined to use a single codebase for both the server and client. However, not every company gives the developer the freedom to use a technology of their choice, and for some good reasons. Using a JavaScript stack for an entire project is the current norm, but there's nothing stopping you from choosing two different technologies for the server side and the client side. 

So how well do Laravel and React fit together? Pretty well, in fact. Although Laravel has documented supported for Vue.js, which is another JavaScript framework, we will be using React for the front-end because it's more popular.

Prerequisites

Before getting started, I am going to assume that you have a basic understanding of the RESTful architecture and how API endpoints work. Also, if you have prior experience in either React or Laravel, you'll be able to make the most out of this tutorial. 

However, if you are new to both the frameworks, worry not. The tutorial is written from a beginner's perspective, and you should be able to catch up without much trouble. You can find the source code for the tutorial over at GitHub.

Installing and Setting Up Your Laravel Project

Laravel uses Composer to manage all the dependencies. So, before getting started with Laravel, download and install Composer on your machine. You might also need to configure the path environment variable so that Composer is accessible globally.

Run the following command to download the laravel installer.

composer global require "laravel/installer"

If you've correctly configured the $PATH variable and added ~/.composer/vendor/bin in your path, you should be able to generate a fresh Laravel project as follows:

laravel new PROJECT-NAME

Alternatively, you can use Composer to create a new project without the laravel installer.

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

If everything goes well, you should be able to serve your application on a development server at http://localhost:8000.

php artisan serve

Note: Artisan is a command-line tool that you can't live without while working with Laravel. Artisan accepts a large list of commands that let you generate code for your application. Run php artisan list to view all of the available artisan commands.

Configuring the Environment

Your application will have a .env file inside the root directory. All the environment-specific configuration information is declared here. Create a database for your application if you haven't already, and add the database details into the .env file.

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=sampledb DB_USERNAME=root DB_PASSWORD= Understanding Models, Routes, and Controllers

Laravel is a framework that follows the Model-View-Controller (MVC) architecture. Broadly speaking, MVC helps you to separate the database queries (the Model) from the logic concerned with how the requests should be processed (the Controller) and how the layout should be rendered (the View). The image below demonstrates the working of a typical Laravel application. 

Laravel's architecture. The controller returns the response and hence the view layer is not required.

Since we are building an API using Laravel, we will limit our discussion to the Model and the Controller. We shall review our options for creating the View in the second part of this tutorial. 

The Router

When the server receives an HTTP request, Laravel tries to match it with a route registered inside any of the route files. All the route files are located inside the routes directory. routes/web.php hosts the route for the web interface, whereas routes/api.php hosts the route for the API. The routes registered in api.php will be prefixed with /api (as in localhost:3000/api). If you need to change this behavior, you should head to the RouteServiceProvider class in /app/Providers/RouteServiceProvider.php and make changes there. 

Since we are building a product-listing application, here are the endpoints for the API and the HTTP actions associated with those endpoints. 

  • GET /products/: Retrieve all products.
  • GET /product/{id}: Retrieve the product that matches the id.
  • POST /products: Create a new product and insert it into the database.
  • PUT /products/{id} : Update an existing product that matches the id.
  • DELETE /products/{id}: Delete the product with the given id.

Let's get the terminology right. GET, POST, PUT and DELETE are the HTTP verbs (more popularly known as HTTP methods) essentially required for building a RESTful service. /products is the URI associated with the products resource. The HTTP methods request the server to perform the desired action on a given resource.

GET, POST, PUT and DELETE are the commonly used REST actions

The router allows you to declare routes for a resource along with the HTTP methods that target that resource. Here is a sample routes file that returns some hard-coded data.

routes/api.php/** ** Basic Routes for a RESTful service: ** ** Route::get($uri, $callback); ** Route::post($uri, $callback); ** Route::put($uri, $callback); ** Route::delete($uri, $callback); ** **/ Route::get('products', function () { return response(['Product 1', 'Product 2', 'Product 3'],200); }); Route::get('products/{product}', function ($productId) { return response()->json(['productId' => "{$productId}"], 200); }); Route::post('products', function() { return response()->json([ 'message' => 'Create success' ], 201); }); Route::put('products/{product}', function() { return response()->json([ 'message' => 'Update success' ], 200); }); Route::delete('products/{product}',function() { return response()->json(null, 204); });

If you want to verify that the routes are working as expected, you should use a tool like POSTMAN or curl.

The Product Model

The products resource needs a model that can interact with the database. Model is the layer that sits on top of the database, hiding away all the database-specific jargon. Laravel uses Eloquent ORM for modeling the database. 

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. 
Laravel Docs

What about the database schema definition? Laravel's migration takes care of that. Artisan has a migration command that lets you define your schema and incrementally update it at a later stage. Let's create a model and a migration for the Product entity. 

$ php artisan make:model Product -m

Note: There are lots of Artisan commands out there, and it's easy to get lost. So every artisan command includes a helper screen that displays additional information such as the options and arguments available. To get to the help page, the name of the command should be preceded with help. Run the following help command to see what the -m option stands for: $ php artisan help make:model.

Here's the migration file generated.

database/migrations/timestamp_create_products_table.php<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProductsTable extends Migration { public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('products'); } }

The up method is called while migrating new tables and columns into the database, whereas the down method is invoked while rolling back a migration. We've created a Schema for a table with three rows: id, created_at, and updated_at. The $table->timestamps() method is responsible for maintaining the created_at and updated_at columns. Let's add a couple more lines to the schema definition.

/* Let's add columns for title, description, price, availability */ public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('title'); $table->text('description'); $table->integer('price'); $table->boolean('availability'); }); }

We've updated the schema with four new columns. Laravel's schema builder supports a variety of column types like string, text, integer, boolean, etc.

To execute the pending migrations, you have to run the following command:

php artisan migrate

By convention, Laravel assumes that the Product model is associated with the products table. However, if you need to associate the model with a custom table name, you can use the $table property to declare the name of the table. The model will then be associated with a table named custom_products.

protected $table = 'custom_products';

But we will keep things simple and go with the convention. The Product model generated is located inside the app/ directory. Although the model class may seem empty, it comes equipped with various query builder methods that you can use to query the database. For instance, you can use Product::all() to retrieve all the products or Product::find(1) to retrieve a particular product with id 1. 

Laravel models have a built-in protection mechanism against mass assignment vulnerability. The fillable property is used to declare the attribute names that can be mass assigned safely. 

app/Product.php/* Add the fillable property into the Product Model */ protected $fillable = ['title', 'description', 'price', 'availability'];

The code above whitelists the title, description, price and availability attributes and treats them as mass assignable. We can now use the Product::create method to insert new rows into the products table. 

Database Seeding

Laravel lets you populate your development and production database with dummy data which you then can use to test your API endpoints. You can create a seed class by executing the following Artisan command.

$ php artisan make:seeder ProductsTableSeeder

The generated seeder files will be placed in the database/seeds directory.

To generate the dummy data, you could use something like str_random(10) that returns a random string. But if you need data that is close enough to the actual data, you should use something like the faker library. Faker is a third-party library that gets shipped with the Laravel framework for generating fake data.

database/seeds/ProductsTableSeeder.phpuse App\Product; class ProductsTableSeeder extends Seeder { public function run() { $faker = \Faker\Factory::create(); // Create 50 product records for ($i = 0; $i < 50; $i++) { Product::create([ 'title' => $faker->title, 'description' => $faker->paragraph, 'price' => $faker->randomNumber(2), 'availability' => $faker->boolean(50) ]); } } }

Execute the db:seed artisan command to populate the database. 

$ php artisan db:seed --class=ProductsTableSeeder

Let's head back to routes/api.php and fill in the missing pieces.

routes/api.php/** **Basic Routes for a RESTful service: **Route::get($uri, $callback); **Route::post($uri, $callback); **Route::put($uri, $callback); **Route::delete($uri, $callback); ** */ Route::get('products', function () { return response(Product::all(),200); }); Route::get('products/{product}', function ($productId) { return response(Product::find($productId), 200); }); Route::post('products', function(Request $request) { $resp = Product::create($request->all()); return $resp; }); Route::put('products/{product}', function(Request $request, $productId) { $product = Product::findOrFail($productId); $product->update($request->all()); return $product; }); Route::delete('products/{product}',function($productId) { Product::find($productId)->delete(); return 204; });The Controller

The route file currently hosts the logic for routing and handling requests. We can move the request handling logic to a Controller class so that our code is better organized and more readable. Let's generate a controller class first.

$ php artisan make:controller ProductsController

The Controller class comprises of various methods (index, show, store, update, and delete) that correspond to different HTTP actions. I've moved the request handling logic from the route to the controller.

app/HTTP/Controllers/ProductsController.php<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Product; class ProductsController extends Controller { public function index() { return Product::all(); } public function show(Product $product) { return $product; } public function store(Request $request) { $product = Product::create($request->all()); return response()->json($product, 201); } public function update(Request $request, Product $product) { $product->update($request->all()); return response()->json($product, 200); } public function delete(Product $product) { $product->delete(); return response()->json(null, 204); } }routes/api.php/** **Basic Routes for a RESTful service: **Route::get($uri, $callback); **Route::post($uri, $callback); **Route::put($uri, $callback); **Route::delete($uri, $callback); ** */ Route::get('products', 'ProductsController@index'); Route::get('products/{product}', 'ProductsController@show'); Route::post('products','ProductsController@store'); Route::put('products/{product}','ProductsController@update'); Route::delete('products/{product}', 'ProductsController@delete');

If you haven't noticed, I've injected an instance of Product into the controller methods. This is an example of Laravel's implicit binding. Laravel tries to match the model instance name Product $product with the URI segment name {product}. If a match is found, an instance of the Product model is injected into the controller actions. If the database doesn't have a product, it returns a 404 error. The end result is the same as before but with less code.

Open up POSTMAN and the endpoints for the product should be working. Make sure you have the Accept : application/json header enabled. 

Validation and Exception Handling

If you head over to a nonexistent resource, this is what you'll see. 

The NotFoundHTTPException is how Laravel displays the 404 error. If you want the server to return a JSON response instead, you will have to change the default exception handling behavior. Laravel has a Handler class dedicated to exception handling located at app/Exceptions/Handler.php. The class primarily has two methods: report() and render(). The report method is useful for reporting and logging exception events, whereas the render method is used to return a response when an exception is encountered. Update the render method to return a JSON response:

app/Exceptions/Handler.phppublic function render($request, Exception $exception) { if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { return response()->json([ 'message' => 'Resource not found' ], 404); } return parent::render($request, $exception); }

Laravel also allows us to validate the incoming HTTP requests using a set of validation rules and automatically return a JSON response if validation failed. The logic for the validation will be placed inside the controller. The Illuminate\Http\Request object provides a validate method which we can use to define the validation rules. Let's add a few validation checks to the store method.

app/HTTP/Controllers/ProductsController.phppublic function store(Request $request) { $this->validate($request, [ 'title' => 'required|unique:products|max:255', 'description' => 'required', 'price' => 'integer', 'availability' => 'boolean', ]); $product = Product::create($request->all()); return response()->json($product, 201); }Summary

We now have a working API for a product listing application. However, the API lacks basic features such as authentication and restricting access to unauthorized users. Laravel has out-of-the-box support for authentication, and building an API for it is relatively easy. I encourage you to implement the authentication API as an exercise. 

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study on Envato Market.

Now that we're done with the back end, we will shift our focus to the front-end concepts. Stay tuned for the second part of the series. Share your thoughts in the comments.

Categories: Web Design

Building A Large-Scale Design System For The U.S. Government (Case Study)

Smashing Magazine - Mon, 10/09/2017 - 13:42
Editor’s Note: We’ve been closely working with Maya on this article, and we’re happy to see the final result now being published on 18F. We highly encourage more teams to share the lessons they learned when building design systems or pattern libraries, and we’re always happy to support them in writing, editing and shaping that article. This post is a re-post of Maya’s final article. Today, there are nearly 30,000 U.
Categories: Web Design

Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js

Tuts+ Code - Web Development - Mon, 10/09/2017 - 06:00
What You'll Be Creating

This topic is a really enjoyable one for me. It's quite common in many web applications to accept user input and save a single record to your database. But what about when your users (or you) want to perform multiple inserts in a single command? 

Enter this article, which will demonstrate how to create a CSV template and a form to upload the CSV file, and how to parse the CSV into a Mongoose Model that will be saved to a MongoDB database.

This article assumes that you have a basic understanding of Mongoose and how it interacts with MongoDB. If you don't, I would suggest reading my Introduction to Mongoose for MongoDB and Node.js article first. This article describes how Mongoose interacts with MongoDB by creating strongly-typed Schemas which a Model is created from. If you already have a good understanding of Mongoose, then let's proceed.

Getting Started

To begin, let's instantiate a new Node.js application. In a command prompt, navigate to where you want to host your Node.js applications and perform the following commands:

mkdir csvimport cd csvimport npm init

I've left all the defaults in place, so my application will start with index.js. Before creating and parsing CSV files, some initial setup needs to be done first. I want to make this a web application; to do that, I'm going to use the Express package to handle all of the nitty-gritty server setup. In your command prompt, install Express by running the following command:

npm install express --save

Since this web application will accept files via a web form, I'm also going to use the Express sub-package Express File Upload. Let's install that now as well:

npm install express-fileupload --save

I now have done enough initial configuration to set up my web application and create a basic web page that will create my file upload form.

Here is my index.js file that sets up my web server:

var app = require('express')(); var fileUpload = require('express-fileupload'); var server = require('http').Server(app); app.use(fileUpload()); server.listen(80); app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html'); });

This example imports Express and the Express File Upload libraries, configures my web application to use the File Upload, and listens on port 80. This example has also created a route using Express at "/" which will be the default landing page for my web application. This route returns an index.html file that contains the web form that will allow a user to upload a CSV file. In my case, I am running on my local computer, so when I visit http://localhost I will see the form that I create in the next example.

Here is my index.html page that creates my form for uploading a CSV file:

<!DOCTYPE html> <html lang="en"> <head> <title>Upload Authors</title> </head> <body> <p>Use the form below to upload a list of authors. Click <a href="/template">here</a> for an example template.</p> <form action="/" method="POST" encType="multipart/form-data"> <input type="file" name="file" accept="*.csv" /><br/><br/> <input type="submit" value="Upload Authors" /> </form> </body> </html>

This HTML file contains two important things:

  1. A link to "/template" that, when clicked, will download a CSV template that can be populated with the information to be imported.
  2. A form with the encType set as multipart/form-data and an input field with a type of file that accepts files with a "csv" extension.

As you may have noticed, the HTML makes reference to an Author template. If you read my Introduction to Mongoose article, I created an Author Schema. In this article, I am going to recreate this Schema and allow the user to bulk import a collection of authors into my MongoDB database. Let's take a look at the Author Schema. Before we do that, though, you probably guessed it—we need to install the Mongoose package:

npm install mongoose --saveCreating the Schema and Model

With Mongoose installed, let's create a new author.js file that will define the Author Schema and Model:

var mongoose = require('mongoose'); var authorSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, name: { firstName: { type: String, required: true }, lastName: String }, biography: String, twitter: { type: String, validate: { validator: function(text) { if (text !== null && text.length > 0) return text.indexOf('https://twitter.com/') === 0; return true; }, message: 'Twitter handle must start with https://twitter.com/' } }, facebook: { type: String, validate: { validator: function(text) { if (text !== null && text.length > 0) return text.indexOf('https://www.facebook.com/') === 0; return true; }, message: 'Facebook Page must start with https://www.facebook.com/' } }, linkedin: { type: String, validate: { validator: function(text) { if (text !== null && text.length > 0) return text.indexOf('https://www.linkedin.com/') === 0; return true; }, message: 'LinkedIn must start with https://www.linkedin.com/' } }, profilePicture: Buffer, created: { type: Date, default: Date.now } }); var Author = mongoose.model('Author', authorSchema); module.exports = Author;

With the Author Schema and Model created, let's switch gears and focus on creating the CSV template that can be downloaded by clicking on the template link. To aid with the CSV template generation, I'm going to use the JSON to CSV package. Let's install that now:

npm install json2csv --save

I'm now going to update my previously created index.js file to include a new route for "/template":

var template = require('./template.js'); app.get('/template', template.get);

I've only included the new code for the template route that is appended to the previous index.js file.

The first thing this code does is include a new template.js file (to be created next) and create a route for "/template". This route will call a get function in the template.js file.

With the Express server updated to include the new route, let's create the new template.js file:

var json2csv = require('json2csv'); exports.get = function(req, res) { var fields = [ 'name.firstName', 'name.lastName', 'biography', 'twitter', 'facebook', 'linkedin' ]; var csv = json2csv({ data: '', fields: fields }); res.set("Content-Disposition", "attachment;filename=authors.csv"); res.set("Content-Type", "application/octet-stream"); res.send(csv); };

This file first includes the previously installed json2csv package. I then create and export a get function. This function accepts the request and response objects from the Express server.

Inside the function, I've created an array of the fields that I want to include in my CSV template. This can be done one of two ways. The first way (that is done in this example) is to create a static list of the fields to be included in the template. The second way is to dynamically create the list of fields by extracting the properties from the Author Schema.

The second way could be done with the following code:

var fields = Object.keys(Author.schema.obj);

I would have liked to use this dynamic method, but it becomes a bit complicated when I don't want to include multiple properties from the Schema to my CSV template. In this case, my template doesn't include the _id and created properties because these will be populated via code. However, if you don't have fields you wish to exclude, the dynamic method will work as well.

Creating the CSV Template

With the array of fields defined, I use the json2csv package to create my CSV template from my JavaScript object. This csv object will be the results of this route.

And finally, using the res property from the Express server, I set two header properties that will force the download of an authors.csv file.

At this point, if you were to run your Node application and navigate to http://localhost in your web browser, the web form would be displayed with a link to download the template. Clicking the link to download the template will allow you to download the authors.csv file to be populated before it is uploaded.

Here is an example of a populated CSV file:

name.firstName,name.lastName,biography,twitter,facebook,linkedin Jamie,Munro,Jamie is a web developer and author,,, Mike,Wilson,Mike is a web developer and Node.js author,,,

This example, when uploaded, will create two authors: myself and a friend who wrote a book on Node.js a few years back. You may notice that at the end of each line are three commas ",,,". This is done to abbreviate the example. I have not populated the social network properties (twitter, facebook, and linkedin).

The puzzle pieces are starting to come together and form a picture. Let's get to the meat and potatoes of this example and parse that CSV file. The index.js file requires some updating to connect to MongoDB and create a new POST route that will accept the file upload:

var app = require('express')(); var fileUpload = require('express-fileupload'); var mongoose = require('mongoose'); var server = require('http').Server(app); app.use(fileUpload()); server.listen(80); mongoose.connect('mongodb://localhost/csvimport'); app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html'); }); var template = require('./template.js'); app.get('/template', template.get); var upload = require('./upload.js'); app.post('/', upload.post);

With a database connection and a new POST route configured, it's time to parse the CSV file. Luckily there are several great libraries that assist with this job. I have chosen to use the fast-csv package that can be installed with the following command:

npm install fast-csv --save

The POST route was created similarly to the template route which invokes a post function from the upload.js file. It is not necessary to place these functions in separate files; however, I like to create separate files for these routes as it helps keep the code nice and organized.

Submitting Data

And finally, let's create the upload.js file that contains the post function that is called when the previously created form is submitted:

var csv = require('fast-csv'); var mongoose = require('mongoose'); var Author = require('./author'); exports.post = function (req, res) { if (!req.files) return res.status(400).send('No files were uploaded.'); var authorFile = req.files.file; var authors = []; csv .fromString(authorFile.data.toString(), { headers: true, ignoreEmpty: true }) .on("data", function(data){ data['_id'] = new mongoose.Types.ObjectId(); authors.push(data); }) .on("end", function(){ Author.create(authors, function(err, documents) { if (err) throw err; }); res.send(authors.length + ' authors have been successfully uploaded.'); }); };

Quite a bit is happening in this file. The first three lines include the necessary packages that will be required to parse and save the CSV data.

Next, the post function is defined and exported for use by the index.js file. Inside this function is where the magic takes place.

The function first checks that there is a file contained in the request body. If there is not, an error is returned indicating that a file must be uploaded.

When a file has been uploaded, a reference to the file is saved to a variable called authorFile. This is done by accessing the files array and the file property in the array. The file property matches the name of my file input name that I first defined in the index.html example.

I've also created an authors array that will be populated as the CSV file is parsed. This array will be used to save the data to the database.

The fast-csv library is now called by leveraging the fromString function. This function accepts the CSV file as a string. I've extracted the string from the authorFile.data property. The data property contains the contents of my uploaded CSV file.

I've included two options to the fast-csv function: headers and ignoreEmpty. These are both set to true. This tells the library that the first line of the CSV file will contain the headers and that empty rows should be ignored.

With the options configured, I have set up two listener functions that are called when the data event and the end event are triggered. The data event is called once for every row of the CSV file. This event contains a JavaScript object of the parsed data.

I update this object to include the _id property of the Author Schema with a new ObjectId. This object is then added to the authors array.

When the CSV file has been fully parsed, the end event is triggered. Inside the event callback function, I call the create function on the Author model, passing the array of authors to it.

If an error occurs trying to save the array, an exception is thrown; otherwise, a success message is displayed to the user indicating how many authors have been uploaded and saved to the database.

If you would like to see the full source code, I've created a GitHub repository with the code.

Conclusion

In my example, I've only uploaded a couple of records. If your use case requires the ability to upload thousands of records, it might be a good idea to save the records in smaller chunks.

This can be done several ways. If I were to implement it, I would suggest updating the data callback function to check the length of the authors array. When the array exceeds your defined length, e.g. 100, call the Author.create function on the array, and then reset the array to empty. This will then save the records in chunks of 100. Be sure to leave the final create call in the end callback function to save the final records.

Enjoy!

Categories: Web Design

Building A Large-Scale Design System: How A Design System Was Created For The U.S. Government (Case Study)

Smashing Magazine - Mon, 10/09/2017 - 05:42

   

Editor's Note: We’ve been closely working with Maya on this article, and we’re happy to see the final result now being published on 18F. We highly encourage more teams to share the lessons they learned when building design systems or pattern libraries, and we’re always happy to support them in writing, editing and shaping that article. This post is a re-post of Maya’s final article.

Today, there are nearly 30,000 U.S. federal websites with almost no consistency between them. Between the hundreds of thousands of government employees working in technology, there’s nothing in common with how these websites are built or maintained.

The post Building A Large-Scale Design System: How A Design System Was Created For The U.S. Government (Case Study) appeared first on Smashing Magazine.

Categories: Web Design

Typography Tips – How to Choose the Right Fonts and Colors for Your Email

In any email marketing campaign, good quality content is paramount but the presentation of that content through typography is also equally important if not more. The design of the...

The post Typography Tips – How to Choose the Right Fonts and Colors for Your Email appeared first on Onextrapixel.

Categories: Web Design

CSS Grid Challenge: Winners and Templates

Smashing Magazine - Fri, 10/06/2017 - 13:55
CSS Grid is the new layout standard for the web, but we still are just getting started with new layout ideas. Many assume that CSS Grid is just a replacement for table layouts, but that’s simply not true. Others might think that we can use CSS Grid to replicate more advanced print layouts, which brings us closer to what’s possible. One of the main reasons behind the idea of the CSS Grid Challenge was to have some starting points for layouts, and show what can be achieved with CSS Grids today.
Categories: Web Design

Pages