TutsForWeb https://tutsforweb.com Laravel Tutorials and Forum Sat, 15 Sep 2018 09:07:20 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 139793619 Best Open Source Android Apps: 10+ Apps To Boost Development Skills https://tutsforweb.com/best-open-source-android-apps-10-apps-to-boost-development-skills/ https://tutsforweb.com/best-open-source-android-apps-10-apps-to-boost-development-skills/#respond Thu, 30 Aug 2018 06:21:07 +0000 https://tutsforweb.com/?p=1976 Open-Source Android AppsBest Open Source Android Apps are great for sharpening your programming skills. They are a valuable resource that can help you become a great developer. You can examine and explore open source apps code and build better apps on top of these projects and launch your own applications. You can watch courses or read books, […]]]> Open-Source Android Apps

Best Open Source Android Apps are great for sharpening your programming skills. They are a valuable resource that can help you become a great developer. You can examine and explore open source apps code and build better apps on top of these projects and launch your own applications.

You can watch courses or read books, blogs, forums, and documentation to learn to programme considerably, but there is no alternative to reading a well documented, fully-functional and well-tested app along with its external resources to master the art of programming.

Here is the list of best open source Android apps that are mostly written in Java from various categories to help you become a professional Android Developer. These apps are also available on the Google Play Store and you can use them before diving right into the code. We have attached the difficulty level, GitHub and Play Store link with each app in the list.

Amaze File Manager

Amaze File Manager is a Material design file manager for Android.

Amaze File Manager best Android App

A file manager is an extremely common app that is natively available on almost all Android devices. You can learn how to build a file manager by reading and examining the Amaze File Manager code. It will teach you how to how to perform file handling across all Android platforms and how to perform basic operations such as create, cut, copy, delete, rename, compress, extract, and encrypt files and folders efficiently.

GitHub: 2070 stars and 730 forks
Play Store: 500,000+ Downloads and 4.3/5.0 Rating
Difficulty: Intermediate

Orbot: Proxy with Tor

Orbot is a free Proxy app that allows other internet apps to use the internet safely without being monitored.

Orbot: Proxy with Tor best Android app

It is very similar to Tor Browser and in fact, it uses Tor to encrypt internet traffic. It then routes this through a series of computers. It has a built-in VPN and any app can use it. It is also the official version of Tor for Android devices. It is designed to protect your security and allow you to be anonymous. They use state of the art of protocols for security. You can use Orfox web browser which is built upon the source code of Tor with Orbot proxy to hide your privacy.

GitHub: 284 stars and 123 forks
Play Store: 10,000,000+ Downloads and 4.3/5.0 Rating
Difficulty: Advanced

Minimal ToDo

Minimal ToDo is a material app with minimal features to make it useful.

Minimal ToDo Best Android App

It is a very simple project that will teach you some of the basic stuff about Android Development. I recommend going through this project if you are a beginner. You will learn about fragments and how to design a decent app.

GitHub: 1458 stars and 625 forks
Play Store: 10,000+ Downloads and 4.5/5.0 Rating
Difficulty: Beginner

Omni Notes

Omni notes is an open source note-taking application for Android.

Omni Notes Best Android App

Omni notes is a big project that has all sorts of note-taking app features. You can add, modify, archive, trash and delete notes. You can share them and search them using full-text search available. Tags and Categories, as well as sketch-note mode, is also available. If you are looking for Google Now integration, you can check out this project because it comes up with its implementation. All in all, it is a big project with a lot of features.

GitHub: 1547 stars and 648 forks
Play Store: 100,000+ Downloads and 4.4/5.0 Rating
Difficulty: Intermediate

2048

The Android port of the 2048 game for offline playing.

2048 best android app

It’s just a web view that loads the HTML files that are stored locally. The code is not too great but you can learn how to use assets and create a very simple game.

GitHub: 703 stars and 626 forks
Play Store: 1,000,000+ Downloads and 4.2/5.0 Rating
Difficulty: Beginner

VLC

VLC Media player Official App for Android.

VLC Best Android App

VLC is a popular and open source media player used by a large number of people and organizations. It is a very big project with a large number of components. You need to be an advanced professional programmer to understand and examine this project.

GitHub: 4043 stars and 1574 forks
Play Store: 100,000,000+ Downloads and 4.4/5.0 Rating
Difficulty: Advanced

LeafPic

LeafPic is an ad-free, open-source and material-designed android gallery alternative.

LeafPic Best Android App

LeafPic is one of the best photo and video gallery application from hundreds of others on the Play Store. It is fluid, material design, and open source available under GPL license v3. You can examine LeafPic’s code to understand how to create a gallery application. This app also offers dynamic theming, image crop and many other features that will help you become a better Android developer.

GitHub: 2580 stars and 1043 forks
Play Store: 50,000+ Downloads
Difficulty: Intermediate

Google I/O 2018

The Official Google I/O 2018 conference app to navigate the conference.

Google I/O 2018 Best Android App

Google I/O is a simple beautifully designed app. Its source code was released after the I/O. With this app, you can explore the conference schedule, save events, get reminders, and much more. This app is written in Kotlin. You can dive into the code and learn how to design a great project. This app is well designed and since this app is developed by Google, you can expect the code quality and design to be great.

GitHub: 17,163 stars and 5,578 forks
Play Store: 500,000+ Downloads and 4.3/5.0 Rating
Difficulty: Intermediate

Easy Sound Recorder

Easy-sound-recorder is a simple sound recording app that uses Material Design Guidelines.

Easy Sound Recorder Best Android App

It is a simple sound recorder app that can help you learn how to work with audio recording in Android. It is a beginner level project that you can use to understand how to create a basic app that implements Material Design along with TabLayout and using CRUD with the filesystem.

GitHub: 874 stars and 491 forks
Play Store: 10,000+ Downloads and 4.2/5.0 Rating
Difficulty: Beginner

DuckDuckGo

DuckDuckGo Privacy Browser that makes privacy simplified.

DuckDuckGo Best Android App

DuckDuckGo is a search engine that focuses on protecting user privacy and avoiding personalized search results. The Android app source code is quite complex and large. This app uses Kotlin and C++. You can dive into this app’s code and learn how to create a fully working and well tested commercial application.

GitHub: 544 stars and 148 forks
Play Store: 1,000,000+ Downloads and 4.4/5.0 Rating
Difficulty: Advanced

]]>
https://tutsforweb.com/best-open-source-android-apps-10-apps-to-boost-development-skills/feed/ 0 1976
Ultimate Collection of Free Professional Resume Templates https://tutsforweb.com/free-resume-templates/ https://tutsforweb.com/free-resume-templates/#respond Sun, 12 Aug 2018 13:35:02 +0000 https://tutsforweb.com/?p=1890 Ultimate Collection of Free Resume TemplatesResume plays an effective role in getting a great job. Writing a resume is not easy for everyone. You should never use a handwritten resume. A resume is your first impression when applying for a job. Resume templates are great because they allow you to make professional and beautiful resume faster. There are literally thousands […]]]> Ultimate Collection of Free Resume Templates

Resume plays an effective role in getting a great job. Writing a resume is not easy for everyone. You should never use a handwritten resume. A resume is your first impression when applying for a job. Resume templates are great because they allow you to make professional and beautiful resume faster. There are literally thousands of resume submitted for a job and you must stand out from the crowd to get any attention. You can use Resume templates and create a professional resume without any designing or creative experience.

Most resumes have four basic sections (Contact information, Education, Objective, and Experience). Hiring managers get the most significant information with these details. While graphical resumes are quite good looking but they are terrible at getting the job done. Instead of showing your hard earned accomplishments, you will be showing pretty pictures and useless graphics.

Experience part of the resume is common for all resumes and it is also quite important. Here you write your professional work experience. If you got a scholarship then don’t forget to mention it.

Recommended Learning:


With the above points in mind, we have made an ultimate collection of free professional and beautiful resume templates. As said earlier graphical resumes, in general, are terrible but we have listed them down because you may find the need to use one. Resumes are available in different formats: HTML, PSD, MS Word, PDF, and Adobe Illustrator.

Professional Text Resume (MS Word)

Professional Text Resume

A very professional resume by Gayle Lackman Macdowell.

Professional Text Resume

This resume is required by Wharton’s MBA program and this one is also designed by Gayle Lackman Macdowell. Both of these resumes are available for free and are designed by her. These resumes can be used for general purpose. They are great because hiring managers can easily see all of your accomplishments. You can download them from the link below in the sample resources section in the link.

Free Ziper Resume Template & Cover Letter (PSD)

Free Ziper Resume Template & Cover Letter (PSD)

Free Clean Resume Template PSD

Free Clean Resume Template PSD

Timeline Vector Resume

Timeline Vector Resume

Four Version Resume Template (EPS)

Four Version Resume Template

Professional Resume CV Template (PSD)

Professional Resume CV Template

Simple Classic Resume Template PSD

Simple Classic Resume Template

Designer Resume Template PSD

Designer Resume Template

Free Professional Resume Template With Cover Letter PSD

Free Professional Resume Template With Cover Letter

Graphic Designer Resume Template (PSD)

Graphic Designer Resume Template

Free Smart Resume/CV With Cover Letter PSD

Free Smart Resume/CV With Cover Letter

Creative Resume CV Template PSD

Creative Resume CV Template

Free Creative CV-Resume Design Template With Cover Letter (AI)

Free Creative CV-Resume Design Template With Cover Letter

Free Stylish Resume Template (DOCX, PDF)

Free Stylish Resume Template

Free Resume Template with Formal Design (PSD)

Free Resume Template with Formal Design

Elegant Modern CV Resume PSD

Elegant Modern CV Resume

Creative Resume Template (AI)

Creative Resume Template

Classy Resume Template PSD

Classy Resume Template

Infographic Resume Template Vector (AI)

Infographic Resume Template Vector

Simple Timeline Resume Template (INDD)

Simple Timeline Resume Template

Brand ID Resume Template PSD

Brand ID Resume Template

Clean CV/Resume Template (PSD)

Clean CV/Resume Template

Free Simple Resume Template PSD

Free Simple Resume Template

Resume PSD

Resume

Creative Resume Design Template PSD

Creative Resume Design Template

Resume Template (INDD,IDML,DOC,DOCX)

Resume Template

Free Resume Vector Template(EPS)

Free Resume Vector Template

Free Resume Template PSD

Free Resume Template

Clean Resume Design PSD

Clean Resume Design

New FREE Resume Template 2018 (AI, MS Word, PSD)

New FREE Resume Template

Free Professional CV/Resume Template PSD

Free Professional CV/Resume Template

Free Resume Template

Free Resume Template

Free Minimal Resume Template(AI, MS Word, PSD)

Free Minimal Resume Template

Minimal Resume Template (AI, PSD, PDF)

Minimal Resume Template

Designer Resume Template PSD

Designer Resume Template

Free Resume Templates (AI)

Free Resume Templates

Modern CV Template (MS Word)

Modern CV Template

Creative Resume CV Template PSD

Creative Resume CV Template

Free Professional Resume Template PSD

Free Professional Resume Template

Awesome free resume for designers

Awesome free resume for designers

Recommended Learning:


 

]]>
https://tutsforweb.com/free-resume-templates/feed/ 0 1890
Best tools to beautify or Unminify CSS for better formatting https://tutsforweb.com/best-tools-to-beautify-unminify-css-for-better-formatting/ https://tutsforweb.com/best-tools-to-beautify-unminify-css-for-better-formatting/#respond Wed, 08 Aug 2018 17:12:35 +0000 https://tutsforweb.com/?p=1859 best tools to beautify or minify CSS codeDevelopers often minify their web code for better performance because minification decreases the file size. Sometimes you want to edit your minified code again. It is extremely difficult to edit your minified code. To make your minified code better formatted and easily editable, we use code beautifier or Unminifier. There are a lot of editors and IDE’s […]]]> best tools to beautify or minify CSS code

Developers often minify their web code for better performance because minification decreases the file size. Sometimes you want to edit your minified code again. It is extremely difficult to edit your minified code. To make your minified code better formatted and easily editable, we use code beautifier or Unminifier. There are a lot of editors and IDE’s as well as online tools available that can readily format your code.

In this post, we have listed the best tools available to unminify or beautify your code. In some of the tools, you can also add formatting options like indentation, spacing and line breaks. These tools can unminify unlimited lines of CSS code. You can also comment your best beautifier in the comment section at the end of the post.

Online tools

Below is the list of online tools that you can use to beautify or unminify your CSS code.

Unminify

Unminify

Unminify is a free online tool to unminify (unpack, deobfuscate) JavaScript, CSS and HTML code, making it readable and pretty. It is a very simple tool. Simply paste your CSS code and click the UNMINIFY button to format your code.

Unminifier

Unminifier

Unminifier tool will unminify, deobfuscate, beautify and format ugly HTML, XML, CSS and JS code to make it readable again. It is a very great tool to minify HTML, XML, CSS, and JS code. Simply paste your code and click the unminify button to unminify your code.

Clean CSS

Clean CSS

Clean CSS tool allows you to format your CSS code. You can also load a CSS file or add a URL to the CSS code and this tool will beautify it.

Free Formatter

Free Formatter

This tool allows you to format a CSS files with the chosen indentation level for optimal readability. It supports 4 indentation levels: 2 spaces, 3 spaces, 4 spaces, and tabs. You can also upload a CSS file to beautify and better format.

Code Beautifier

Code Beautifier

Code Beautifier is a CSS formatter and optimizer based on csstidy 1.3. It comes up with a lot of customizations that you can use to format your CSS code the way you want.

Online CSS Unminifier

Online CSS Unminifier

A simple online tool to unminify CSS. It is a simple minify tool that also allows you to specify the width of the tab.

CSS Unpacker

CSS Unpacker

CSS Unpacker allows you to unpack your CSS files to make them more readable.

Online CSS Minify/Unminify Tool

Online CSS Minify/Unminify Tool

It is a simple tool to optimize and clean your CSS code and remove any unnecessary characters from the file to reduce its size. You can minify as well as unminify your CSS code using this great tool.

CSS Minifiers Online – CSS Unminify

CSS Minifiers Online - CSS Unminify

A simple CSS Minifier online – unminify – beautify/format tool. Just paste your CSS code into the box and push the button. That’s all.

CSS Unminifier

CSS Unminifier

A simple CSS Unminifier and beautifier to make CSS easy to read and debug.

Softwares

Below is the list of code editors, IDE’s or extensions that allows you to unminify or beautify your CSS code.

Sublime Text

HTML-CSS-JS Prettify Sublime

You can beautify or unminify your code in Sublime Text using the HTML-CSS-JS Prettify extension. Simply install it using Sublime Package Manager and then go into the Tools -> Command Palette and type htmlprettify. Now open the HTML, CSS, or JS file and then pop out the console in Sublime Text from View -> Show Console and type view.run_command("htmlprettify").

Atom Beautify

Atom Beautify

Atom Beautify allows you to beautify HTML, CSS, JavaScript, PHP, Python, Ruby, Java, C, C++, C#, Objective-C, CoffeeScript, TypeScript, Coldfusion, SQL, and more in Atom. You can simply install it using the apm by running the command apm install atom-beautify. Now open the Command palette, type Beautify and run Beautify Editor.

Brackets Beautify

Brackets Beautify Extension

Beautify HTML, CSS, and Javascript in Adobe Brackets. You can install the latest release of this extension using the built-in brackets extension manager which downloads the extension from extension registry. Use the toolbar button with the wand icon to beautify your code.

WebStorm/PhpStorm

PhpStorm

In WebStorm/PhpStorm IDE’s, it is very easy to beautify your code. Simple open your CSS file and then choose Code | Reformat Code, or press Ctrl + Alt + L to beautify your code. It works with HTML, CSS, JS, PHP and many other languages.

Also, see:
20 Best Material Design Frameworks And Libraries

]]>
https://tutsforweb.com/best-tools-to-beautify-unminify-css-for-better-formatting/feed/ 0 1859
20 Best Material Design Frameworks and Libraries https://tutsforweb.com/20-best-material-design-frameworks-and-libraries/ https://tutsforweb.com/20-best-material-design-frameworks-and-libraries/#respond Sat, 30 Jun 2018 11:37:25 +0000 https://tutsforweb.com/?p=1774 Material Design Framework Featured ImageMaterial design was developed by Google as the design language in 2014. Material design takes the mobile-first approach. The idea of material design is to create a unified experience for all the company’s web and mobile apps across platforms and device sizes. Material design uses grid-based layouts, proper animations, responsiveness, transition, and shadows. It is […]]]> Material Design Framework Featured Image

Material design was developed by Google as the design language in 2014. Material design takes the mobile-first approach. The idea of material design is to create a unified experience for all the company’s web and mobile apps across platforms and device sizes.

Material design uses grid-based layouts, proper animations, responsiveness, transition, and shadows. It is designed from the thinking of how a paper would look like as a user interface.

Material design has been adopted in many Google products including Android, Gmail, and Youtube. It is also used by many major companies on their websites and mobile apps such as Whatsapp. It is increasingly becoming popular nowadays.

There are many Material Design based front end frameworks and libraries offering implementation with usable components and styles. In this post, we have listed best material design frameworks for developers.

Materialize

Materialize Material Design Framework

Materialize is a modern responsive front-end framework based on Material Design. It is really easy to get started because of its detailed documentation. It also comes with a SASS version, which allows users to choose which components to include. Materialize is one of the most popular Material design frameworks. It is ideal for getting started with Material design.

  • Maintainers: Alvin Wang
  • Release Date: 2014
  • GitHub Popularity: 33165 stars and 4565 forks
  • License: MIT

Muse-UI

Muse-UI Material Design Framework

Muse-UI is one of the lightest CSS frameworks that follows Material Design Guidelines. The file size of CSS and JS files gzipped and minified amount up to 12KB. Muse UI is based on the Vue 2.0 elegant Material Design UI component library. The framework supports React, customizations via SASS and has more than 40 UI components.

  • Maintainers: Andres Morey
  • Release Date: 2016
  • GitHub Popularity: 6120 stars and 750 forks
  • License: MIT

Material UI

Material UI contains React components that implement Google Material Design Guidelines. If you are using React Framework, Material UI is the framework to go to. It contains dark and light themes for users to choose. It has become one of the most popular frameworks for implementing Material Design Guidelines.

  • Maintainers: Material-UI Team
  • Release Date: 2014
  • GitHub Popularity: 38083 stars and 6927 forks
  • License: MIT

Material Design Lite

Material Design Lite Material Design Framework

Material Design Limit is a framework originally developed by Google that lets you add a Material Design look and feel to your websites. It looks great, does not rely on any third party JavaScript frameworks, and is optimized for cross-device use. It supports SASS preprocessor. Material Lite is not supported by Google, but you can get community support for the framework.

  • Maintainers: Google Team
  • Release Date: 2015
  • GitHub Popularity: 30271 stars and 5220 forks
  • License: Apache License 2.0

Material Components for the Web

Material Components for the Web Framework

Material Components for the web is a framework designed and maintained by Google engineers for implementing Material Design Guidelines. It is the successor of Material Design Lite. It follows total adherence to the Material design guidelines since it is developed and maintained by Google. You can easily integrate Material design for the web with other JavaScript Frameworks and Libraries.

  • Maintainers: Material Components Team
  • Release Date: 2016
  • GitHub Popularity: 9476 stars and 1079 forks
  • License: Apache License 2.0

Material Design for Bootstrap

Material Design for Bootstrap Framework

Material Design for Bootstrap is a great option Bootstrap users. It is based on the Bootstrap framework and you can use it to create components for Bootstrap 3 and Bootstrap 4. You can easily get started with the great documentation. Material design for Bootstrap has a great active community.

  • Maintainers: Federico Zivolo
  • Release Date: 2014
  • GitHub Popularity: 19358 stars and 3301 forks
  • License: MIT

Polymer

Polymer Material Design Framework

Polymer is a library that provides a set of features for creating fast, reusable web components which you can import and use in your projects. It is developed by Google and community on GitHub. Polymer paper elements collection implements Google’s Material Design Guidelines. You can also use other polymer components to achieve material design layouts. It is used by Youtube, Google Earth, Netflix and many other big companies.

Angular Material

Angular-Material Material Design Framework

Angular Material is a Material Design Framework built by Angular Team at Google. It is built particularly for implementing Material Design Guidelines in AngularJS. It comes with a huge collection of reusable and well-tested components, documentation with many working examples and their code, and an active community.

Angular Material library exists separately for the AngularJS version 1 and AngularJS version 2+.

Here are the details for the Angular Material for version 2+.

  • Maintainers: Angular Team
  • Release Date: 2016
  • GitHub Popularity: 14900 stars and 3704 forks
  • License: MIT

Below are the details for the Angular Material for version 1

Vuetify

Vuetify Material Design Framework

Vuetify is a semantic component framework for Vue 2. It provides reusable components that make building applications easy. It is created according to Google’s Material Design Guidelines and has a great documentation along with code examples that you can use in your projects. Vuetify has a great active community which is definitely a huge plus.

  • Maintainers: Vuetify.js Team
  • Release Date: 2016
  • GitHub Popularity: 11571 stars and 955 forks
  • License: MIT

JFoenix

JFOENIX Material Design Framework

JFoenix is a Java library that implements Google Material design guidelines using Java Components. It contains classic Material components that you can implement using JavaFX.

  • Maintainers: JFoeniX
  • Release Date: 2015
  • GitHub Popularity: 2702 stars and 535 forks
  • License: Apache License 2.0

Propeller

Propeller Material Design Framework

Propeller is a front-end responsive framework based on Google’s Material Design Standards and Bootstrap. It has a detailed documentation of its library components as well as code examples that you can use in your projects.

  • Maintainers: Digicorp Team
  • Release Date: 2016
  • GitHub Popularity: 1123 stars and 143 forks
  • License: MIT

Framework7

Framework7 Material Design Framework

Framework7 is an HTML framework to develop hybrid mobile apps for iOS and Android. It allows you to build web apps with native iOS and Android native look. It is also easy to prototype app as soon as possible. Framework 7 has a Material theme that you can use to build apps with the native Android look.

  • Maintainers: Framework7 Team
  • Release Date: 2014
  • GitHub Popularity: 12548 stars and 2708 forks
  • License: MIT

Material Foundation

Material Foundation Material Design Framework

Zurb Foundation is an amazing tool for building responsive web applications. Material Foundation allows you to create your web applications using the foundation framework implementing Material Design By Google. It works pretty well but it lacks some of the material components. Also, the development is no longer happening which is bad news.

Ionic Material

Ionic Material Design Framework

Ionic Material is an extension for Ionic hybrid mobile apps framework which means you do not have to make changes to your Ionic hybrid apps to give them Google Material Design look. It adds new classes, methods, and helpers to create the Material look without interfering with code behavior or styles.

Materia Theme for Bootstrap

bootswatch materia material design framework

Bootswatch team makes a lot of Bootstrap themes. One of their themes implements Material Design Guidelines called Materia. It contains some of the classic material components but it is great if you are working with Bootstrap. You don’t have to make changes to your project other than replacing the Bootstrap CSS files with the theme files to get Material Design look.

  • Maintainers: Thomas Park
  • Release Date: 2012
  • GitHub Popularity: 10372 stars and 2947 forks
  • License: MIT

Material

Material Material Design Framework

Material is based on fully responsive front-end framework Bootstrap 4. It implements Material components to Bootstrap but also adds many traditional Material Design Elements such as cards. It comes with a great documentation guide that will help you start from scratch easily.

Surface

Surface Material Design Framework

Surface is a CSS only framework that implements many Material Design components without any dependency. It is a lightweight single CSS file with the size of 5.7kb minified and Gzipped. It does not contain any JavaScript.

  • Maintainers: Ben Mildren
  • Release Date: 2015
  • GitHub Popularity: 263 stars and 51 forks
  • License: MIT

Essence

Essence Material Design Framework

Essence is a CSS framework that implements Material Design Guidelines by Google. It is based on Facebook React.js library. You can build great looking web and mobile apps super-fast. Essence does not have a great active community but you can still use it in your projects.

  • Maintainers: Evo Forge Team
  • Release Date: 2015
  • GitHub Popularity: 413 stars and 53 forks
  • License: MIT

Lumx

Lumx Material Design Framework

Lumx allows you to implement Material Design Guidelines in a pixel-perfect way. It is based on AngularJS. Lumx uses jQuery and Sass toolset Bourbon for styles that make it easy for customization. It also uses Velocity for creating animations. The documentation of the framework contains examples with code that you can use in your projects. It helps you design beautiful applications faster and easier.

  • Maintainers: Lumapps Team
  • Release Date: 2014
  • GitHub Popularity: 2011 stars and 296 forks
  • License: MIT

Phonon

Phonon Material Design Framework

Phonon is a framework for building Hybrid mobile apps. It supports Apache Cordova and PhoneGap. Phonon is only 62.1kb which makes it a very light framework. It closely follows Google’s Material Design Guidelines.

  • Maintainers: Quarkdev Team
  • Release Date: 2014
  • GitHub Popularity: 377 stars and 102 forks
  • License: MIT

Bonus: Material Icons

Material Design Icons

Material Design Icons is the official Icon set from Google. It’s not exactly a Material Design Framework, but you can use it in your Material Design projects. The icons are designed under Material Design Guidelines. You can choose from a huge list of icons and use them in your projects. You can easily implement them in your projects using a font collection or symbols and sprites.

  • Maintainers: Google Team
  • Release Date: 2014
  • GitHub Popularity: 35244 stars and 7000 forks
  • License: Apache License 2.0

Find Top 10+ Best Vue.Js Frameworks

]]>
https://tutsforweb.com/20-best-material-design-frameworks-and-libraries/feed/ 0 1774
How to set up Task Scheduling with Cron job in Laravel https://tutsforweb.com/how-to-set-up-task-scheduling-cron-job-in-laravel/ https://tutsforweb.com/how-to-set-up-task-scheduling-cron-job-in-laravel/#respond Wed, 20 Jun 2018 19:00:30 +0000 https://tutsforweb.com/?p=1630 Laravel Cron Job Task SchedulerApplications require some tasks to be run periodically on the server. It could be sending promotional emails, optimizing database, creating backups or generating site traffic report. To automate these tasks, a task scheduling system is required. Laravel Cron Job offers an elegant Task Scheduling mechanism. Cron Cron is a time-based task scheduler in Unix/Linux operating systems. It […]]]> Laravel Cron Job Task Scheduler

Applications require some tasks to be run periodically on the server. It could be sending promotional emails, optimizing database, creating backups or generating site traffic report. To automate these tasks, a task scheduling system is required. Laravel Cron Job offers an elegant Task Scheduling mechanism.

Cron

Cron is a time-based task scheduler in Unix/Linux operating systems. It runs shell commands at a pre-specified time period. Cron uses a configuration file called crontab also known as Cron table to manage the task scheduling process.

Crontab contains all the Cron jobs related to a specific task. Cron jobs are composed of two parts, the Cron expression, and a shell command that needs to be run.

* * * * * command/to/run

In the Cron expression above (* * * * *), each field is an option for determining the task schedule frequency. These options represent minute, hour, day of the month, month and day of the week in the given order. Asterisk symbol means all possible values. So, the above command will run every minute.

The Cron job below will be executed at 6:20 on 10th of every month.

6 20 10 * * command/to/run

You can learn more about Cron job on Wikipedia. However, Laravel Cron Job Scheduling makes the whole process very easy.

Laravel Cron Job

Laravel Cron Job is an inbuilt task manager that gives your applications the ability to execute specific commands like sending a slack notification or removing inactive users at a periodic time. We will be using the latest version of Laravel, which is 5.6 at the time of writing this article.

You need a Linux Operating System to run Cron Jobs. This tutorial also assumes a fair knowledge of PHP and Laravel.

Creating a new Project

In this tutorial, we will create a simple laravel application to demonstrate task scheduling. Create a new Laravel project by running the following command.

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

Create your Scheduled Task in Laravel

There are different ways you can define scheduled tasks in laravel. Let’s go through each of them to understand how they can be implemented in Laravel.

Create New Artisan Command

cd into your project and run the following command to create a new artisan command class:

php artisan make:command WordOfTheDay

The above command will create a new command file, WordOfTheDay.php, in the app/Console/Commands directory. Navigate to the file and you will find the following code in it:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class WordOfTheDay extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:name';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
    }
}

In this code, the following line contains the name and the signature of the command.

protected $signature = 'command:name';

Replace the words command:name with word:day. This is what we will call this when running the command to perform the task.

protected $signature = 'word:day';

Above code also contains the description property. This is where you place the actual description of what this command will do. Description will be shown when the Artisan list command is executed alongside the signature. Change the description of the command to:

protected $description = 'Send a Daily email to all users with a word and its meaning';

Handle method is called whenever the command is executed. This is where we place the code for doing the specific task. This is how the WordOfTheDay.php file looks with the handle method and all other changes in place:

<?php

namespace App\Console\Commands;

use App\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class WordOfTheDay extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'word:day';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send a Daily email to all users with a word and its meaning';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $words = [
            'aberration' => 'a state or condition markedly different from the norm',
            'convivial' => 'occupied with or fond of the pleasures of good company',
            'diaphanous' => 'so thin as to transmit light',
            'elegy' => 'a mournful poem; a lament for the dead',
            'ostensible' => 'appearing as such but not necessarily so'
        ];

        // Finding a random word
        $key = array_rand($words);
        $value = $words[$key];

        $users = User::all();
        foreach ($users as $user) {
            Mail::raw("{$key} -> {$value}", function ($mail) use ($user) {
                $mail->from('info@tutsforweb.com');
                $mail->to($user->email)
                    ->subject('Word of the Day');
            });
        }

        $this->info('Word of the Day sent to All Users');
    }
}

Above code will select a random word from the array and send emails to every user with the word.

Registering the Command

Now that you have created the command, you will need to register it in the Kernel.

Go to app/Console/Kernel.php file that looks like this

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

In this file, we register the command class in the commands property and we schedule commands to be executed at periodic intervals in the schedule method. This is where we handle all the Cron Jobs in Laravel.

Change this file with the contents below. We have simply added our WordOfTheDay class to the commands property and schedule it to run every day.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\WordOfTheDay::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('word:day')
            ->daily();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

Now, if you run the php artisan list command in the terminal, you will see your command has been registered. You will be able to see the command name with the signature and description.

Laravel Cron Job Command

Setup, database and mail credentials in the .env file and make sure you have users in the database. Execute the command itself on the terminal:

php artisan word:day

Command will be executed with the signature that is placed in protected $signature = 'command:name'. You will also see the log message in the terminal.

Laravel Cron Job Execute

Using Closure/Callback Method

Laravel Task Scheduler allows you to execute a callback or a closure periodically using the call method. Let’s add code in the schedule method of app/Console/Kernel.php Here’s the contents of the class with only the schedule method.

<?php

namespace App\Console;

use App\User;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            User::where('spam_count', '>', 100)
                ->get()
                ->each
                ->delete();
        })->hourly();
    }
}

We have passed the closure as the first parameter to the call method. We have set the frequency of the task to hourly, so it will execute every hour. In the call method, we are simply removing users with spam count of more than 100.

Exec Command

Laravel also allows you to schedule shell commands so that you could issue commands to the operating system and external applications. We use the exec method to execute a shell command.

Here’s a simple example, that allows you to take backup of your code every month.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->exec(
            'cp -r ' . base_path() . " " . base_path('../backups/' . date('jY'))
        )->monthly();
    }
}

exec method will run the command you would pass as the first argument. In the code above, it simply copies your laravel project to the backups folder. The backups folder will be followed by the day of the month and a numeric representation of the year. You can also schedule Laravel Jobs in the Task Scheduler the same way we scheduled Artisan commands and closures. Let’s take a look at the Task Scheduler in detail.

Task Scheduler in Laravel

Task Scheduler in Laravel executes the artisan command, shell, or a callback periodically on the defined time. To do this, we use the schedule method in app/Console/Kernel.php like we discussed earlier.

protected function schedule(Schedule $schedule)
{
    $schedule->command('word:day')
        ->daily();
}

$schedule->command('word:day') is where we define which command needs to be executed and ->daily(); defines the frequency of execution. There are some more time intervals that we can define. You can replace ->daily(); with another time interval option from the following list. You can find more about Task Scheduling in Laravel Documentation.

Method Description
->cron(‘* * * * * *’); Run the task on a custom Cron schedule
->everyMinute(); Run the task every minute
->everyFiveMinutes(); Run the task every five minutes
->everyTenMinutes(); Run the task every ten minutes
->everyFifteenMinutes(); Run the task every fifteen minutes
->everyThirtyMinutes(); Run the task every thirty minutes
->hourly(); Run the task every hour
->hourlyAt(17); Run the task every hour at 17 mins past the hour
->daily(); Run the task every day at midnight
->dailyAt(’13:00′); Run the task every day at 13:00
->twiceDaily(1, 13); Run the task daily at 1:00 & 13:00
->weekly(); Run the task every week
->weeklyOn(1, ‘8:00’); Run the task every week on Tuesday at 8:00
->monthly(); Run the task every month
->monthlyOn(4, ’15:00′); Run the task every month on the 4th at 15:00
->quarterly(); Run the task every quarter
->yearly(); Run the task every year
->timezone(‘America/New_York’); Set the timezone

Starting the Laravel Scheduler

Let’s setup the Cron Jobs to run automatically without initiating manually by running the command. To start the Laravel Scheduler itself, we only need to add one Cron job which executes every minute. Go to your terminal, ssh into your server, cd into your project and run this command.

crontab -e

This will open the server Crontab file, paste the code below into the file, save and then exit.

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

Do not forget to replace /path/to/artisan with the full path to the Artisan command of your Laravel Application.

One of the most important advantages of Laravel Task Scheduler is that we can focus on creating commands, writing logic and Laravel will take care of the rest. It is manageable by other co-workers because it is now tracked by version control.

Learn more about Laravel:
How to create REST API with authentication using Laravel Passport.

]]>
https://tutsforweb.com/how-to-set-up-task-scheduling-cron-job-in-laravel/feed/ 0 1634
Laravel Passport – Create REST API with authentication https://tutsforweb.com/laravel-passport-create-rest-api-with-authentication/ https://tutsforweb.com/laravel-passport-create-rest-api-with-authentication/#comments Thu, 31 May 2018 14:49:08 +0000 https://tutsforweb.com/?p=1604 Laravel Passport AuthenticationIn this tutorial, we will see how to use laravel passport authentication in your Laravel application. We will also build a simple Product CRUD (Create, Read, Update and Delete) using Laravel Passport Authentication. Laravel already provides tradition login forms authentication, but what if you want to use APIs? APIs use tokens for authenticating users, because […]]]> Laravel Passport Authentication

In this tutorial, we will see how to use laravel passport authentication in your Laravel application. We will also build a simple Product CRUD (Create, Read, Update and Delete) using Laravel Passport Authentication.

Laravel already provides tradition login forms authentication, but what if you want to use APIs? APIs use tokens for authenticating users, because they do not use sessions. When a user login via API, a token is generated and sent to the user which is used for authentication purposes. Laravel provides Passport to work with API Authentication without any difficulty.

Let’s see how to setup and configure Laravel Passport for API Authentication and RESTful APIs in a Laravel application.

Creating a new project

Let’s start by creating a new Laravel project. Run the following command to create a new project.

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

Install Package

We need to install Laravel Passport package via the composer dependency manager. Run the following command to require the package.

composer require laravel/passport

Adding Laravel Passport

Laravel Passport requires some steps to set up properly.

Service Provider

I am using Laravel 5.6 which is the latest version of laravel right now which automatically registers package using package auto discovery. If you are using laravel 5.4 or below, you need to add Service Provider in the config/app.php file. So, open the file and add the Service Provider in the providers array.

'providers' => [
    ....
    Laravel\Passport\PassportServiceProvider::class,
]

Migration and Installation

Setup database credentials in .env file. Laravel Passport comes up with migration for passport tables that are required to be in our database. Passport Migrations are used for storing tokens and client information. Run migration command to migrate schemas to your database.

php artisan migrate

Next, it is required to install passport using the command below. It will generate encryption keys required to generate secret access tokens.

php artisan passport:install

Passport Configure

In this step, we need to make changes in our Laravel application to complete passport configuration.

app/User.php

Add Laravel\Passport\HasApiTokens trait to your User model. It will provide few helper methods.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

AuthServiceProvider

Add Passport::routes method in the boot method of your AuthServiceProvider. It will generate necessary routes. This is how the app/Providers/AuthServiceProvider.php will look like after changes.

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}

config/auth.php

In the config/auth.php file, set driver to the passport.

return [
    ....

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

    ....
]

Create Route

Let’s create API routes. Add routes in the routes/api.php file.

Route::post('login', 'PassportController@login');
Route::post('register', 'PassportController@register');

Route::middleware('auth:api')->group(function () {
    Route::get('user', 'PassportController@details');

    Route::resource('products', 'ProductController');
});

Create Controller for Authentication

Let’s set up our logic for Authentication. Create Passport Controller by running the following command.

php artisan make:controller PassportController

Copy the contents below to app/Http/Controllers/PassportController.php

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class PassportController extends Controller
{
    /**
     * Handles Registration Request
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|min:3',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);

        $token = $user->createToken('TutsForWeb')->accessToken;

        return response()->json(['token' => $token], 200);
    }

    /**
     * Handles Login Request
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = [
            'email' => $request->email,
            'password' => $request->password
        ];

        if (auth()->attempt($credentials)) {
            $token = auth()->user()->createToken('TutsForWeb')->accessToken;
            return response()->json(['token' => $token], 200);
        } else {
            return response()->json(['error' => 'UnAuthorised'], 401);
        }
    }

    /**
     * Returns Authenticated User Details
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function details()
    {
        return response()->json(['user' => auth()->user()], 200);
    }
}

Let me explain what’s happening in the code above

In the register method, we validate the request data and then create the user. We then create the token using the createToken method and passing the name as an argument. Finally, we return token in a JSON response.

In the login method, we attempt to authenticate using the request details. Then, we return an appropriate response based on the success or failure of the attempt.

In the details method, we simply return the user eloquent model.

Create Product CRUD

Let’s create a product CRUD. Run the following command to create Product Model, Migration and Controller.

php artisan make:model Product -mc

It will create a new database migration file create_products_table.php in database/migrations directory. Update the up method to the code below.

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->string('name');
        $table->integer('price');
        $table->timestamps();

        $table->foreign('user_id')
            ->references('id')
            ->on('users');
    });
}

Now, add a fillable property to the Product model. Open the Product.php file in the app directory.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name', 'price'
    ];
}

Now, run database migration.

php artisan migrate

Now, let’s add a product relationship method in the app/User.php file.

public function products()
{
    return $this->hasMany(Product::class);
}

Open the ProductController.php file in app/Http/Controllers directory. Copy the contents below to the Product Controller.

<?php

namespace App\Http\Controllers;

use App\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index()
    {
        $products = auth()->user()->products;

        return response()->json([
            'success' => true,
            'data' => $products
        ]);
    }

    public function show($id)
    {
        $product = auth()->user()->products()->find($id);

        if (!$product) {
            return response()->json([
                'success' => false,
                'message' => 'Product with id ' . $id . ' not found'
            ], 400);
        }

        return response()->json([
            'success' => true,
            'data' => $product->toArray()
        ], 400);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'price' => 'required|integer'
        ]);

        $product = new Product();
        $product->name = $request->name;
        $product->price = $request->price;

        if (auth()->user()->products()->save($product))
            return response()->json([
                'success' => true,
                'data' => $product->toArray()
            ]);
        else
            return response()->json([
                'success' => false,
                'message' => 'Product could not be added'
            ], 500);
    }

    public function update(Request $request, $id)
    {
        $product = auth()->user()->products()->find($id);

        if (!$product) {
            return response()->json([
                'success' => false,
                'message' => 'Product with id ' . $id . ' not found'
            ], 400);
        }

        $updated = $product->fill($request->all())->save();

        if ($updated)
            return response()->json([
                'success' => true
            ]);
        else
            return response()->json([
                'success' => false,
                'message' => 'Product could not be updated'
            ], 500);
    }

    public function destroy($id)
    {
        $product = auth()->user()->products()->find($id);

        if (!$product) {
            return response()->json([
                'success' => false,
                'message' => 'Product with id ' . $id . ' not found'
            ], 400);
        }

        if ($product->delete()) {
            return response()->json([
                'success' => true
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Product could not be deleted'
            ], 500);
        }
    }
}

Testing

Now, our logic is complete, let’s start testing. We will be testing it on PHP development server but you can use virtual host if you want. Run the following command to serve the application on the PHP development server.

php artisan serve

Now, let’s test our API endpoints using an API testing tool like Postman.

Register API

Laravel Passport Authentication Register

Login API

Laravel Passport Authentication Login

Details API

When testing Details API or any API that requires a user to be authenticated, you need to specify two headers. You must specify access token as a Bearer token in the Authorization header. Basically, you have to concatenate the access token that you received after login and registration with the Bearer followed by a space.

'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '. $accessToken,
]

Laravel Passport Authentication Details

Products Index API

Passport Authentication Product Index

Product Store API

Passport Authentication Product store

Product Show API

Passport Authentication Product show

Product Update API

Passport Authentication Product update

Product Delete API

Passport Authentication Product delete

Full Source code for this tutorial is available at

Learn More
Restful API In Laravel 5.6 Using jwt Authentication

]]>
https://tutsforweb.com/laravel-passport-create-rest-api-with-authentication/feed/ 1 1604
How to create custom 404 page in Laravel https://tutsforweb.com/how-to-create-custom-404-page-laravel/ https://tutsforweb.com/how-to-create-custom-404-page-laravel/#comments Wed, 23 May 2018 20:12:16 +0000 https://tutsforweb.com/?p=1581 Laravel create custom 404 pageIn this tutorial, we will see how to create custom 404 page in Laravel. PHP Exceptions are similar to the exceptions in other programming languages. Exceptions are thrown when an error or an unknown event occurs. All PHP Exceptions extends the base Exception class. Laravel provides app/Exceptions/Handler.php class that checks for all exceptions thrown in […]]]> Laravel create custom 404 page

In this tutorial, we will see how to create custom 404 page in Laravel.

PHP Exceptions are similar to the exceptions in other programming languages. Exceptions are thrown when an error or an unknown event occurs. All PHP Exceptions extends the base Exception class.

Laravel provides app/Exceptions/Handler.php class that checks for all exceptions thrown in the application. Basically, every exception thrown in the application can be configured in this file and an appropriate response can be generated.

In this tutorial, we will see how to create a custom response for a 404 page. We are using Laravel 5.6. By default, Laravel returns a Whoops page back. We will see how to return a custom page depending on the exception. This will help you return a custom page for every HTTP Exception you want.

When someone hits a route that is not present, your site shows an error. It affects your SEO as well.

So, let’s see how we can manage 404 page, other HTTP exceptions, and Custom Exceptions in Laravel.

Setup Laravel Project

Let’s create a new laravel project. Run the following command to create a new project in a folder named errors.

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

Handling exceptions

All of the changes related to handling exceptions will be done in app/Exceptions/Handler.php. We will return a view when an error comes.

Custom 404 Page

Let’s create a custom 404 page in Laravel. In the app/Exceptions/Handler.php file, modify the render method.

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception)) {
        if ($exception->getStatusCode() == 404) {
            return response()->view('errors.' . '404', [], 404);
        }
    }

    return parent::render($request, $exception);
}

In the render method, we check if the exception is an HTTP exception. It is important because we are calling getStatusCode() method which is only available on HTTP exceptions. If the status code is 404, we return a view errors.404 with a status code as well. You can change the name of the view if you want.

We have to create a view for the 404 page. So, create a new view file errors/404.blade.php.

<!DOCTYPE html>
<html>
<head>
    <title>Page not found - 404</title>
</head>
<body>


The page your looking for is not available

</body>
</html>

If you want to create a custom page for any other HTTP exception, simply add a new if statement and change 404 with the new status code. Here’s the render method for handling 404 and 500 status code custom pages.

public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception)) {
        if ($exception->getStatusCode() == 404) {
            return response()->view('errors.' . '404', [], 404);
        }
        
        if ($exception->getStatusCode() == 500) {
            return response()->view('errors.' . '500', [], 500);
        }
    }

    return parent::render($request, $exception);
}

Here’s the 404 response from our application.

custom 404 page laravel

Custom HTTP Exceptions pages

We can also automate this process. It would be great if we only have to create a new view file for the exception. The need to add code to the app/Exceptions/Handler.php file for every HTTP exception will no longer be required. In the app/Exceptions/Handler.php modify the render method.

public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception)) {
        if (view()->exists('errors.' . $exception->getStatusCode())) {
            return response()->view('errors.' . $exception->getStatusCode(), [], $exception->getStatusCode());
        }
    }

    return parent::render($request, $exception);
}

Now, you are only required to create a view with the status code of the exception. render method will check if the view exists with the status code of the exception. If the view is present, it will simply return an HTTP response with that view and the status code.

For Example, we can create errors/404.blade.php for 404 error pages, errors/500.blade.php for 500 error pages and so on.

Handling Custom Exceptions

Let’s first create a custom exception. Run the following code to create an exception named TestingHttpException.

php artisan make:exception TestingHttpException

In the app/Exceptions/Handler.php file, modify the render method.

public function render($request, Exception $exception)
{
    if ($exception instanceof TestingHttpException) {
        return response()->view('errors.testing');
    }
    return parent::render($request, $exception);
}

If the exception is an instance of TestingHttpException, it will return errors.testing view.

You can also use the abort method with 404 code and it will serve an HTTP response with the custom 404 page.

You can use these techniques for handling all types of exceptions.

Learn more about Laravel:
Laravel Auth: Login With Email Or Username In One Field
Sending Notifications to Telegram Messenger with Laravel

]]>
https://tutsforweb.com/how-to-create-custom-404-page-laravel/feed/ 1 1581
Restful API In Laravel 5.6 Using jwt Authentication https://tutsforweb.com/restful-api-in-laravel-56-using-jwt-authentication/ https://tutsforweb.com/restful-api-in-laravel-56-using-jwt-authentication/#comments Wed, 23 May 2018 05:32:12 +0000 https://tutsforweb.com/?p=1546 Restful API In Laravel 5.6 Using jwt AuthenticationIn this article, we will learn how to build restful API in Laravel using JWT Authentication. JWT stands for JSON Web Tokens. We will also create a fully functional CRUD for user products using API. API’s are great when working with cross-platform applications. In addition to a website, your product may have an android and […]]]> Restful API In Laravel 5.6 Using jwt Authentication

In this article, we will learn how to build restful API in Laravel using JWT Authentication. JWT stands for JSON Web Tokens. We will also create a fully functional CRUD for user products using API.

API’s are great when working with cross-platform applications. In addition to a website, your product may have an android and iOS app. In such cases, API’s are great because you can write different front ends without changing any backend code. When working with API, you simply hit a GET, POST or different kind of request with some arguments and server returns some data in JSON (JavaScript Object Notation) format which is handled by the client-side application.

Details

Let’s first write down our application details and features. We will build a basic user products list with restful API in laravel using JWT authentication.

A User will be able to

  • sign up and create a new account
  • log-in to their account
  • log out to discard the token and leave the application
  • get the details of the logged in user
  • retrieve a list of products available for the user
  • find a specific product by id
  • add a new product to the user product list
  • edit an existing product details
  • delete an existing product from the user list

A User requires

  • name
  • email
  • password

A Product requires

  • name
  • price
  • quantity

Creating a new project

Let’s start by creating a new laravel project by running the following command.

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

It will create a new laravel project in the folder named jwt.

Configuring JWT Package

We will be using tymondesigns/jwt-auth package for working with JWT in Laravel.

Installing tymon/jwt-auth package

Let’s install this package in our Laravel application. If you are using Laravel version 5.5 or above, run the following command to require a dev-develop version of jwt package.

composer require tymon/jwt-auth:dev-develop --prefer-source

If you are using the laravel version 5.4 or less, run the following command

composer require tymon/jwt-auth

For versions less than 5.5, you are also required to set service provider and alias in config/app.php file.

'providers' => [
    ....
    Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
    ....
],
'aliases' => [
    ....
    'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory',
    ....
],

If you are using version 5.5 or above, laravel does it automatically using Package Auto-Discovery.

Publishing Configuration File

Publish the configuration file using the following command for versions 5.5 or above

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

If you are using previous versions of laravel, run the following command to publish the configuration

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

Above command will generate a config/jwt.php configuration file. Here’s the configuration file without any comments.

<?php

return [

    'secret' => env('JWT_SECRET'),

    'keys' => [

        'public' => env('JWT_PUBLIC_KEY'),

        'private' => env('JWT_PRIVATE_KEY'),

        'passphrase' => env('JWT_PASSPHRASE'),
    ],

    'ttl' => env('JWT_TTL', 60),

    'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),

    'algo' => env('JWT_ALGO', 'HS256'),

    'required_claims' => [
        'iss',
        'iat',
        'exp',
        'nbf',
        'sub',
        'jti',
    ],

    'persistent_claims' => [
        // 'foo',
        // 'bar',
    ],

    'lock_subject' => true,

    'leeway' => env('JWT_LEEWAY', 0),

    'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),

    'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),

    'decrypt_cookies' => false,

    'providers' => [
        'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class,

        'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,

        'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
    ],
];

Generate JWT Key

JWT tokens will be signed with an encryption key. Run the following command for laravel 5.5 or above to generate the secret key used to sign the tokens.

php artisan jwt:secret

For versions below 5.5

php artisan jwt:generate

This tutorial uses laravel 5.6. Next steps of the tutorial are only tested for laravel 5.5 and 5.6. Tutorial steps below may not work for laravel 5.4 or less. You may consider the documentation for laravel previous versions.

Registering Middleware

JWT auth package comes up with middlewares that we can use. Register auth.jwt middleware in app/Http/Kernel.php

protected $routeMiddleware = [
    ....
    'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,
];

This middleware verifies that the user is authenticated by checking the token sent with the request. If the user is not authenticated, the middleware will throw UnauthorizedHttpException exception.

Set up Routes

We will set up routes for all the endpoints that we discussed at the start of the tutorial. Open up routes/api.php and copy the routes below to your file.

Route::post('login', 'ApiController@login');
Route::post('register', 'ApiController@register');

Route::group(['middleware' => 'auth.jwt'], function () {
    Route::get('logout', 'ApiController@logout');

    Route::get('user', 'ApiController@getAuthUser');

    Route::get('products', 'ProductController@index');
    Route::get('products/{id}', 'ProductController@show');
    Route::post('products', 'ProductController@store');
    Route::put('products/{id}', 'ProductController@update');
    Route::delete('products/{id}', 'ProductController@destroy');
});

Update User Model

JWT requires implementing the Tymon\JWTAuth\Contracts\JWTSubject interface on the User model. This interface requires implementing two methods getJWTIdentifier and getJWTCustomClaims. Update app/User.php file with the contents present below.

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

JWT Authentication Logic

Let’s write the logic for restful API in laravel using JWT authentication.

User registration requires name, email, and password. So, let’s create a form request to validate the data. Create a Form request named RegisterAuthRequest by running the following command:

php artisan make:request RegisterAuthRequest

It will create RegisterAuthRequest.php file in app/Http/Requests directory. Paste the code below into the file.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RegisterAuthRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|string',
            'email' => 'required|email|unique:users',
            'password' => 'required|string|min:6|max:10'
        ];
    }
}

Create a new ApiController by running the command:

php artisan make:controller ApiController

This will create the ApiController.php file in app/Http/Controllers directory. Paste the code below into the file.

<?php

namespace App\Http\Controllers;

use App\Http\Requests\RegisterAuthRequest;
use App\User;
use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class ApiController extends Controller
{
    public $loginAfterSignUp = true;

    public function register(RegisterAuthRequest $request)
    {
        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);
        $user->save();

        if ($this->loginAfterSignUp) {
            return $this->login($request);
        }

        return response()->json([
            'success' => true,
            'data' => $user
        ], 200);
    }

    public function login(Request $request)
    {
        $input = $request->only('email', 'password');
        $jwt_token = null;

        if (!$jwt_token = JWTAuth::attempt($input)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid Email or Password',
            ], 401);
        }

        return response()->json([
            'success' => true,
            'token' => $jwt_token,
        ]);
    }

    public function logout(Request $request)
    {
        $this->validate($request, [
            'token' => 'required'
        ]);

        try {
            JWTAuth::invalidate($request->token);

            return response()->json([
                'success' => true,
                'message' => 'User logged out successfully'
            ]);
        } catch (JWTException $exception) {
            return response()->json([
                'success' => false,
                'message' => 'Sorry, the user cannot be logged out'
            ], 500);
        }
    }

    public function getAuthUser(Request $request)
    {
        $this->validate($request, [
            'token' => 'required'
        ]);

        $user = JWTAuth::authenticate($request->token);

        return response()->json(['user' => $user]);
    }
}

Let me explain what’s happening in the code above.

In the register method, we accept RegisterAuthRequest. A user is created with the data present in the request. If the loginAfterSignUp property is true, it will log-in the user by calling the login method after registering. Otherwise, a successful response is returned with the user data.

In the login method, we get a subset of the request only containing email and password. JWTAuth::attempt() is called with input as the argument and the response is saved in a variable. If false is returned from the attempt method, we return a failure response. Otherwise, a success response is returned.

In the logout method, the request is validated that it contains the token field. The token is invalidated by calling the invalidate method and a successful response is returned. If the JWTException exception caught, a failure response is returned.

In the getAuthUser method, the request is validated that it contains the token field. Then the authenticate method is called which returns the authenticated user. Finally, the response with the user is returned.

Authentication part is now complete.

Building the Product Part

To create the product part, we will need a Product model, controller, and migration. Run the following command to create the Product model, controller, and migration.

php artisan make:model Product -mc

It will create a new database migration file create_products_table.php in database/migrations directory. Update the up method.

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->string('name');
        $table->integer('price');
        $table->integer('quantity');
        $table->timestamps();

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });
}

Add a fillable property to the Product model. Open the Product.php file in the app directory and add the property.

protected $fillable = [
    'name', 'price', 'quantity'
];

Now set up your database credentials in the .env file and migrate the database by running the following command.

php artisan migrate

Now, we have to add a relationship in the User model to retrieve the related products. In app/User.php add the following method.

public function products()
{
    return $this->hasMany(Product::class);
}

Open the ProductController.php file in app/Http/Controllers directory. Add the following use directives at the beginning of the file overwriting the previous one.

use App\Product;
use Illuminate\Http\Request;
use JWTAuth;

Now we will implement five methods.

  • index, to get a list of all the products for the authenticated user
  • show, to get a specific product by its id
  • store, to store a new product to the list of products
  • update, to update product details by its id
  • destroy, to delete a product from the list by its id

Add a constructor to get the authenticated user and save it in the user property.

protected $user;

public function __construct()
{
    $this->user = JWTAuth::parseToken()->authenticate();
}

parseToken will parse the token from the request and authenticate method will authenticate the user via the token.

Let’s add the index method.

public function index()
{
    return $this->user
        ->products()
        ->get(['name', 'price', 'quantity'])
        ->toArray();
}

Above code is very easy. We are simply using eloquent to get all of the user products and then we convert the results into an array. Finally, we return it. Laravel will automatically convert it into JSON and create a 200 success response code.

Moving on to implement the show method.

public function show($id)
{
    $product = $this->user->products()->find($id);

    if (!$product) {
        return response()->json([
            'success' => false,
            'message' => 'Sorry, product with id ' . $id . ' cannot be found'
        ], 400);
    }

    return $product;
}

This one is also easy to understand. We simply find the product with the id. If the product is not present, a failure 400 response is returned. Otherwise, the product is returned.

Next method is the store method.

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
        'price' => 'required|integer',
        'quantity' => 'required|integer'
    ]);

    $product = new Product();
    $product->name = $request->name;
    $product->price = $request->price;
    $product->quantity = $request->quantity;

    if ($this->user->products()->save($product))
        return response()->json([
            'success' => true,
            'product' => $product
        ]);
    else
        return response()->json([
            'success' => false,
            'message' => 'Sorry, product could not be added'
        ], 500);
}

In the store method, the request is validated that it contains name, price, and quantity. Then, a new Product model is created with the data present in the request. If the product is saved successfully in the database, a success response is returned. Otherwise, a failure 500 custom response is returned.

Let’s implement the update method.

public function update(Request $request, $id)
{
    $product = $this->user->products()->find($id);

    if (!$product) {
        return response()->json([
            'success' => false,
            'message' => 'Sorry, product with id ' . $id . ' cannot be found'
        ], 400);
    }

    $updated = $product->fill($request->all())
        ->save();

    if ($updated) {
        return response()->json([
            'success' => true
        ]);
    } else {
        return response()->json([
            'success' => false,
            'message' => 'Sorry, product could not be updated'
        ], 500);
    }
}

In the update method, we find the product with the id. If the product is not present, a 400 response is returned. Then we update the product details with the details present in the request by using the fill method. Updated product model is then saved in the database. If the record updates successfully, a 200 success response is returned. Otherwise, a 500 internal server error response is returned to the client.

Now, let’s implement the destroy method.

public function destroy($id)
{
    $product = $this->user->products()->find($id);

    if (!$product) {
        return response()->json([
            'success' => false,
            'message' => 'Sorry, product with id ' . $id . ' cannot be found'
        ], 400);
    }

    if ($product->delete()) {
        return response()->json([
            'success' => true
        ]);
    } else {
        return response()->json([
            'success' => false,
            'message' => 'Product could not be deleted'
        ], 500);
    }
}

In the destroy method, we find the product with its id. If the product is not present, a 400 response is returned. Then we delete the product and return an appropriate response based on the success of the delete operation.

The controller code is now complete. Here is the full controller code.

Testing

Let’s first test the authentication process. We will be using serve command to serve the application on the development server. You can use virtual host if you want. Run the following command to serve the application.

php artisan serve

It will start a development server at localhost:8000

For testing restful API’s, we will use Postman. Let’s make a call to the register route after filling the request body.

laravel postman register

Send the request and you will get a token back.

laravel api token

Our user is now registered and authenticated. We can check the login route by sending another request. It will send a 200 response with the token.

laravel api login

Let’s retrieve the user details.

laravel api user

Testing authentication is complete. Let’s test the product part. First store the product.

laravel api products

Now, let’s retrieve the product by requesting the index method.

laravel api products

You can test other routes and they will work.

Full Source Code for this tutorial is available at .

]]>
https://tutsforweb.com/restful-api-in-laravel-56-using-jwt-authentication/feed/ 8 1546
Launching TutsForWeb Forum for Laravel Developers https://tutsforweb.com/launching-tutsforweb-forum-for-laravel-developers/ https://tutsforweb.com/launching-tutsforweb-forum-for-laravel-developers/#respond Wed, 16 May 2018 05:59:43 +0000 https://tutsforweb.com/?p=1522 tutsforweb laravel forumGood news for all of you. We have launched TutsForWeb Forum for Laravel Developers. We are trying to create a great community of laravel developers. You can join our forum at forum.tutsforweb.com. You can ask questions and get answers from other users and me. I will be there to help you. Your participation is highly […]]]> tutsforweb laravel forum

Good news for all of you. We have launched TutsForWeb Forum for Laravel Developers. We are trying to create a great community of laravel developers.

You can join our forum at forum.tutsforweb.com.

You can ask questions and get answers from other users and me. I will be there to help you.

Your participation is highly appreciated. Ask questions about topics related to laravel and answer other users questions as well. You can also post howto on the forum as well. I hope we will be able to build a great community.

I would love to see you being a part of TutsForWeb community. Thanks for being a part of TutsForWeb.

]]>
https://tutsforweb.com/launching-tutsforweb-forum-for-laravel-developers/feed/ 0 1522
15 Awesome Laravel collection methods https://tutsforweb.com/15-laravel-collection-methods/ https://tutsforweb.com/15-laravel-collection-methods/#comments Wed, 25 Apr 2018 07:50:56 +0000 https://tutsforweb.com/?p=1456 15 Awesome Laravel collection methodsLaravel Eloquent uses Collections to return the results. Collections contains very useful methods that makes them very powerful and helpful to use. You can filter them, modify them and much more with them very conveniently. We will be looking at laravel collection methods in this tutorial. Collections are not only limited to eloquent results but […]]]> 15 Awesome Laravel collection methods

Laravel Eloquent uses Collections to return the results. Collections contains very useful methods that makes them very powerful and helpful to use. You can filter them, modify them and much more with them very conveniently. We will be looking at laravel collection methods in this tutorial.

Collections are not only limited to eloquent results but can be used separately. Eloquent results uses collections. You can simply create a collection by passing an array to collect helper function. All of the next collection methods listed below are applicable to both the eloquent collections and collections itself as well.

Let’s say, you have a post model. You find all the posts with php category.

$posts = App\Post::where('category', 'php')->get();

The above command returns a collection. A collection is a laravel class that uses arrays internally and adds many features to them.

You can create a collection simply by using collect method like this.

$collection = collect([
    [
        'user_id' => '1',
        'title' => 'Helpers in Laravel',
        'content' => 'Create custom helpers in Laravel',
        'category' => 'php'
    ],
    [
        'user_id' => '2',
        'title' => 'Testing in Laravel',
        'content' => 'Testing File Uploads in Laravel',
        'category' => 'php'
    ],
    [
        'user_id' => '3',
        'title' => 'Telegram Bot',
        'content' => 'Crypto Telegram Bot in Laravel',
        'category' => 'php'
    ],
]);

Above array is actually the values of our Post model. In this tutorial, we will be using this array for simplification. Remember everything will work the same way for the eloquent as well.

That’s how you can simply create collections. You can apply all the collection helper method available in Laravel.

When we apply helper methods on eloquent collections, they do not query the database. All the results that we want to get from the database are first taken and then we use collection methods to filter and modify them without any querying to the database.

filter()

filter, one of the most useful laravel collection method, allows you to filter the collection with a callback. It only passes those items that return true. All the other items are removed. filter returns a new instance without changing the original instance. It accepts value and key as two parameters in the callback.

$filter = $collection->filter(function($value, $key) {
    if ($value['user_id'] == 2) {
        return true;
    }
});

$filter->all();

all method returns the underlying array. Above code returns the following response.

[
    1 => [
        "user_id" => 2,
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ]
]

search()

search method is used to search the collection for a given value. If the value is present in the collection, the key of the value is returned. If the value does not matches any item, false is returned.

$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);

$names->search('Jason');

// 2

By default, the search is done using loose comparison. You can pass true as the second argument to the search method to use strict comparison.

You can also pass your own callback function to the search method. It will return the key of the first item that passes the callback truth test.

$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);

$names->search(function($value, $key) {
    return strlen($value) == 6;
});

// 3

chunk()

chunk method is used to split the collection into multiple smaller collections of given size. It is useful displaying collections into the grid.

$prices = collect([18, 23, 65, 36, 97, 43, 81]);

$prices = $prices->chunk(3);

$prices->toArray();

Response from the above code.

[
    0 => [
        0 => 18,
        1 => 23,
        2 => 65
    ],
    1 => [
        3 => 36,
        4 => 97,
        5 => 43
    ],
    2 => [
        6 => 81
    ]
]

dump()

dump method dumps the collection’s items. It is useful for debugging and finding what’s inside the collection at any point in the collection pipeline.

$collection->whereIn('user_id', [1, 2])
    ->dump()
    ->where('user_id', 1);

dump response from the above code.

laravel collection methods dump

map()

map method is used to iterate through the full collection. It accepts a callback as an argument. value and the key is passed to the callback. Callback can modify the values and return them. Finally, a new collection instance of modified items is returned.

$changed = $collection->map(function ($value, $key) {
    $value['user_id'] += 1;
    return $value;
});

return $changed->all();

Basically, it incremented user_id by one.

Response from the above code looks like this.

[
    [
        "user_id" => 2,
        "title" => "Helpers in Laravel",
        "content" => "Create custom helpers in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => 3,
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => 4,
        "title" => "Telegram Bot",
        "content" => "Crypto Telegram Bot in Laravel",
        "category" => "php"
    ]
];

zip()

Zip method appends the values of the given array with the values of the collection. Values are added to the same index meaning first value of the array will be merged with the first value of the collection. Here, I am using the collection array that we created above. It works the same way with eloquent collections as well.

$zipped = $collection->zip([1, 2, 3]);

$zipped->all();

JSON Response looks like this.

laravel collection methods zip

So, that’s basically it. If the count of the array is less than the count of collections, laravel will add null at the end of remaining collection elements. Also, if the count of the array is greater than the count of collections, laravel will add a null for the collection elements followed by the subsequent array value.

whereNotIn()

You can use whereNotIn method to simply filter the collection by a key value not contained within the given array. It’s basically the opposite of whereIn. Also, this method uses loose comparison == when matching values.

Let’s filter the $collection where user_id is neither 1 nor 2.

$collection->whereNotIn('user_id', [1, 2]);

The above statement will return only the last item from the $collection created above. The first argument is the key and the second argument is an array of values. In case of eloquent, the first argument will be the name of the column and the second argument will be an array of values.

max()

max method returns the maximum value of a given key. You can find the maximum user_id by calling max. It’s normally used for things like price or any other number but for the sake of demonstration let’s use user_id. It can also be used with strings and in that case, Z > a.

$collection->max('user_id');

Above statement will return the maximum user_id which in our case is 3.

pluck()

pluck method returns all of the values for a key. It is useful for extracting values of one column.

$title = $collection->pluck('title');
$title->all();

The result looks like this.

[
  "Helpers in Laravel",
  "Testing in Laravel",
  "Telegram Bot"
]

When working with eloquent, you can pass a column name as an argument to extract its values. pluck also accepts a second argument and in the case of eloquent collections, it can be another column name. It will result in collection keyed by the values of the second argument.

$title = $collection->pluck('user_id', 'title');
$title->all();

The result looks like this:

[
    "Helpers in Laravel" => 1,
    "Testing in Laravel" => 2,
    "Telegram Bot" => 3
]

each()

each is a simple method for iterating over the full collection. It accepts a callback with two arguments: item it is iterating through and the key. Key is 0 based index.

$collection->each(function ($item, $key) {
    info($item['user_id']);
});

Above, it is simply logging the user_id of each item.

When logging over eloquent collections, you can access all the column values as item properties. Here’s how we can iterate through all posts.

$posts = App\Post::all();

$posts->each(function ($item, $key) {
    // Do something
});

If you return false from your callback, it will stop iterating over items.

$collection->each(function ($item, $key) {
    // Tasks
    if ($key == 1) {
        return false;
    }
});

tap()

tap() method allows you to tap into the collection at any point. It accepts a callback and passes and passes the collection to it. You can do anything with the items without changing the collection itself. So, you can use tap to peak into the collection at any point without mutating the collection.

$collection->whereNotIn('user_id', 3)
    ->tap(function ($collection) {
        $collection = $collection->where('user_id', 1);
        info($collection->values());
    })
    ->all();

In the tap method used above, we modified the collection and then logged the value. You can do anything you want with the collection inside the tap. Response from the above command is:

[
    [
        "user_id" => "1",
        "title" => "Helpers in Laravel",
        "content" => "Create custom helpers in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => "2",
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ]
]

You can see that tap does not modify the collection instance. Learn more about tap helper function and tap collection method in detail.

pipe()

pipe method is very similar to the tap method in a sense that both of them are used inside the collection pipeline. pipe method passes the collection to the callback and return the result.

$collection->pipe(function($collection) {
    return $collection->min('user_id');
});

Response from the above command is 1. If you return an instance of collection from the pipe callback, you can chain further methods as well.

contains()

contains method simply checks if the collection contains a given value. It is only true when you pass a single argument.

$contains = collect(['country' => 'USA', 'state' => 'NY']);

$contains->contains('USA');
// true

$contains->contains('UK');
// false

If you pass a key / value pair to the contains method, it will check whether the given pair exists or not.

$collection->contains('user_id', '1');
// true

$collection->contains('title', 'Not Found Title');
// false

You can also pass a callback as an argument to the callback method. Callback will run for every item in the collection and if any of them passes the truth test, it will return true else false.

$collection->contains(function ($value, $key) {
    return strlen($value['title']) < 13;
});
// true

Callback accepts two arguments value of the currently iterating item and the key. Here we are simply checking if the length of the title is less than 13. In Telegram Bot it is 12, so it returned true.

forget()

forget simply removes the item from the collection. You simply pass a key and it will remove that item from the collection.

$forget = collect(['country' => 'usa', 'state' => 'ny']);

$forget->forget('country')->all();

Response from the above code:

[
    "state" => "ny"
]

forget does not work on multi-dimensional arrays.

avg()

avg method returns the average value. You simply pass a key as an argument and the avg method returns the average. You can also use the average method which is basically an alias for avg.

$avg = collect([
    ['shoes' => 10],
    ['shoes' => 35],
    ['shoes' => 7],
    ['shoes' => 68],
])->avg('shoes');

Above code returns 30 which is the average of all four numbers. If you do not pass any key to avg method and all the items are numbers, it will return the avg of all numbers. If the key is not passed as an argument and the collection contains key / value pairs, avg method returns 0.

$avg = collect([12, 32, 54, 92, 37]);

$avg->avg();

The above code returns 45.4 which is the average of all five numbers.

You can use these laravel collection methods to work with collection in your own projects.

]]>
https://tutsforweb.com/15-laravel-collection-methods/feed/ 1 1456