#laravel collection to array of objects
Explore tagged Tumblr posts
Text
Why Choose Laravel For Your Web Development Projects: Key Benefits Unveiled - Sohojware
In the ever-evolving landscape of web development, choosing the right framework is paramount to a project's success. Laravel, a PHP framework renowned for its expressiveness and powerful features, has become a favorite among developers worldwide. But what makes Laravel stand out, and why should you consider it for your next web development project? Sohojware, a leading web development company Sohojware, dives deep to unveil the key benefits of leveraging Laravel for your next project.
Speed Up Development with Laravel's MVC Architecture
Laravel adheres to the Model-View-Controller (MVC) architectural pattern. This separation of concerns fosters a clean and organized codebase, promoting faster development cycles. Developers at Sohojware can concentrate on building the core functionalities (models) while crafting a user-friendly interface (views) independently. This structured approach streamlines the development process, saving you valuable time and resources.
Enhanced Security with Built-in Features
Security is a top priority for any web application. Laravel empowers developers with a plethora of built-in security features to safeguard your project. Features like CSRF (Cross-Site Request Forgery) protection and password hashing mechanisms help shield your application from vulnerabilities. Sohojware's Laravel developers stay updated on the latest security practices to ensure your web app remains secure.
Effortless Authentication and Authorization
Laravel streamlines user authentication and authorization processes. The framework provides pre-built libraries for handling user registration, login, and role-based access control. This eliminates the need to reinvent the wheel, allowing Sohojware's developers to focus on crafting unique functionalities specific to your project.
Scalability for Future Growth
As your business flourishes, your web application needs to adapt. Laravel's powerful architecture and eloquent syntax make it exceptionally scalable. Sohojware's developers can effortlessly integrate new features and functionalities as your project grows, ensuring your Laravel application seamlessly accommodates your expanding needs.
Blade Templating Engine: Power Meets Simplicity
Laravel's Blade templating engine is a gem for developers. It offers a clean and concise syntax that simplifies the creation of dynamic web pages. Blade templates enable Sohojware's developers to seamlessly integrate PHP logic with HTML, streamlining the development process and fostering the creation of elegant and maintainable code.
Artisan: A Powerful Command-Line Interface
Laravel's Artisan CLI (Command-Line Interface) is a developer's best friend. Sohojware's developers leverage Artisan to automate repetitive tasks such as generating controllers, models, and migrations. This not only saves development time but also minimizes errors and promotes code consistency.
A Flourishing Community and Abundant Resources
The Laravel community is one of its greatest strengths. With a vast array of online tutorials, forums, and well-documented resources, developers can readily find solutions and support. Sohojware's Laravel developers consistently stay updated with the latest Laravel trends and best practices through this vibrant community.
Package Ecosystem for Enhanced Functionality
The Laravel ecosystem boasts a rich collection of third-party packages. These pre-built functionalities can be seamlessly integrated into your project, saving development time and effort. Sohojware's developers can leverage these packages to implement features like social media logins, e-commerce functionalities, and payment gateways, all without reinventing the wheel.
Object-Oriented Programming for Maintainable Code
Laravel heavily leans on object-oriented programming (OOP) principles. This approach fosters code reusability and maintainability. Sohojware's developers can create well-structured, modular code that's easier to understand, modify, and extend in the future.
Testing Made Easy with Laravel's Built-in Tools
Laravel offers a powerful suite of testing tools that empower developers to write unit tests and integration tests. Sohojware's developers can leverage these tools to ensure the quality and stability of your web application throughout the development lifecycle.
Is Laravel Right for Your Project?
While Laravel offers a multitude of benefits, it's not a one-size-fits-all solution. Here at Sohojware, our experienced developers can help you determine if Laravel is the ideal framework for your specific project requirements.
Sohojware: Your Trusted Laravel Development Partner
Sohojware's team of skilled Laravel developers is passionate about crafting innovative and secure web applications. We leverage the power of Laravel to deliver exceptional results that align with your unique business goals. Contact Sohojware today to discuss your project requirements and explore how Laravel can empower your web development journey.
FAQs
1. Is Laravel difficult to learn?
Laravel has a well-structured and expressive syntax, making it relatively easier to learn compared to other PHP frameworks. However, a basic understanding of PHP is recommended before diving into Laravel. Sohojware offers a variety of resources and consultations to help you get started with Laravel development.
2. What are the pros and cons of using Laravel?
Pros:
MVC architecture for clean and organized code
Built-in security features
Effortless authentication and authorization
Exceptional scalability
Powerful Blade templating engine
Artisan CLI for automation
Flourishing community and resources
Rich package ecosystem
Object-oriented approach for maintainable code
Built-in testing tools
Cons:
Laravel might be slightly overkill for very simple projects.
The initial learning curve can be steeper compared to some basic frameworks.
3. How much does it cost to develop a Laravel application?
The cost of developing a Laravel application depends on various factors like project complexity, features required, and development timeline. Sohojware offers flexible engagement models to cater to your specific budget and project needs. Contact us for a free consultation to receive a custom quote.
4. How long does it take to develop a Laravel application?
The development timeline for a Laravel application hinges on the project's scope and features. Sohojware's experienced developers can provide an accurate timeline estimate after a thorough analysis of your project requirements.
5. Does Sohojware provide ongoing maintenance and support for Laravel applications?
Absolutely! Sohojware offers comprehensive maintenance and support packages to ensure your Laravel application remains secure, optimized, and up-to-date with the latest Laravel releases.
Sohojware is confident that Laravel's powerful features and our team's expertise can deliver a high-performing and scalable web application that propels your business forward. Contact us today to embark on your Laravel development journey!
1 note
·
View note
Text
Laravel Development Trends: What's Evolving in Web Development for 2024

Laravel stands out as a leading PHP framework in 2024, widely embraced for its elegant syntax, user-friendly nature, and rich library ecosystem. Its popularity continues to surge among developers globally, with projections indicating further growth throughout the year.
What is Laravel?
Laravel, an open-source PHP framework, equips developers with an extensive set of tools to craft bespoke web applications efficiently. While initially leveraging Symfony, another PHP framework, Laravel has since developed its own identity, empowering developers to construct full-stack applications with optimal productivity.
The main objective of Laravel development is to improve the accessibility of web applications. This is accomplished through its expressive and refined syntax, enabling developers to produce clean, testable, and maintainable code efficiently.
Laravel owes its success to its meticulously crafted design patterns, adherence to best practices, and strict coding standards.
Orbitwebtech provides an array of development solutions that render it a compelling option for businesses and organizations. Its Laravel development services encompass a spectrum of offerings, spanning from bespoke application development to seamless API integration, alongside comprehensive maintenance and support provisions.
Laravel stands out as a versatile option for developers due to its seamless integration with various PHP libraries and robust data binding capabilities. These features empower developers to seamlessly incorporate a variety of tools and technologies into their projects. As a result of these advantages, Laravel has risen to prominence as one of the leading PHP frameworks available today.
Moreover, Laravel presents numerous advantages. These include prioritizing convention over configuration, facilitating swift development, offering robust routing and validation capabilities, seamless integration with various PHP libraries, and efficient data binding. These features collectively contribute to making Laravel one of the most desirable PHP frameworks available.
In this article, we'll delve into the most recent trends shaping Laravel in 2024 and discuss effective web development strategies to elevate your Laravel-powered websites and applications.
Here's a list of the latest trends in Laravel development for 2024
1) Microservices Architecture
2) Serverless Architecture
3) Real-time Applications
4) Cloud-Native Applications
5) Laravel Headless CMS
6) GraphQL API
7) Artificial Intelligence and Machine Learning
Why is Laravel development in demand?
Laravel development has experienced a surge in popularity in recent years, attributable to several factors.
Elegance and Simplicity:
Laravel boasts a sophisticated yet straightforward syntax, facilitating an accessible learning curve and seamless utilization. Additionally, it offers a plethora of pre-developed functionalities and tools, empowering developers to construct web applications swiftly and effectively.
Strong Community Support:
The Laravel framework benefits from a vibrant community of developers who actively contribute to its growth, provide assistance, and develop numerous open-source packages for integration into Laravel projects. This collaborative ecosystem fosters continuous innovation and enhancement within the Laravel community, driving its evolution and improvement over time.
Security:
Laravel incorporates numerous native security measures, including password hashing, encryption, and CSRF protection, which collectively enhance the security of web applications developed on the platform.
Business proprietors choose to enlist dedicated Laravel developers to capitalize on the Laravel framework's functionalities in enhancing data protection, privacy, and security for their web applications.
The framework incorporates various security measures, including but not limited to password management, user authentication, data encryption, and additional protective features.
Scalability:
Laravel's architecture is tailored to accommodate expansive applications, rendering it a prime selection for enterprises with enduring expansion strategies.
Modular Structure:
Laravel adopts a modular architecture, which facilitates developers in efficiently organizing and managing their codebase. This design enables straightforward customization and expansion of the framework.
Testing Capabilities:
Laravel offers integrated testing functionalities empowering developers to craft and execute tests for their applications, guaranteeing functionality and bug-free operation.
What is Laravel Volt?
Laravel Volt stands out as a fresh front-end template debut in the Laravel 8.x ecosystem. It represents a contemporary, nimble, and adaptable option, offering a polished and sophisticated user interface tailored for Laravel applications.
Volt utilizes cutting-edge web development technologies like Tailwind CSS, Alpine.js, and Blade templates. It incorporates a variety of pre-designed UI components, including forms, buttons, modals, and tables, which can be effortlessly tailored to fit the requirements of any Laravel project.
Volt is specifically crafted to seamlessly integrate with Laravel's authentication system, facilitating the effortless incorporation of user authentication and authorization within Laravel applications. Additionally, it offers a range of pre-designed pages, including login, register, forgot password, and email verification pages, which can be tailored to align with the branding of any Laravel application.
Volt stands out for its simplicity and user-friendly interface. Its clean and modern design, customizable through Laravel's Blade templating engine, is a key advantage. With Volt, developers can efficiently create responsive web applications without the need to start from scratch in UI design.
Laravel vs Volt | What are the differences?
Laravel, a popular PHP framework, and Volt, a compiled language, serve distinct purposes in web development. While Laravel advocates convention over configuration, offering streamlined development processes, Volt provides developers with explicit control over configuration details. The decision between the two ultimately hinges on project requirements and the preferences of the development team.
What is Laravel Folio?
Laravel Folio offers a package or library that delivers page-based routing functionality tailored for Laravel, mirroring the capabilities of Next.js in React applications Laravel Folio, recently introduced by Taylor Otwell, empowers developers with the ability to outline pages using a file-based format. This innovative package streamlines the process by automatically generating routes corresponding to the defined page structure.
Laravel Folio seems to offer valuable functionality for developers interested in creating page-based applications using Laravel. It could be particularly beneficial for individuals familiar with frameworks like Next.js.
The Best Laravel Development Trends in 2024
1) Microservices Architecture
In 2024, the microservices architecture is anticipated to maintain its upward trajectory in popularity. This architectural approach enables developers to craft applications that are both scalable and resilient by decomposing them into smaller, more manageable components.
Microservices architecture is a methodology for constructing software systems composed of independently functioning and loosely coupled services. Laravel, a popular PHP framework, offers a diverse array of features and tools conducive to implementing a microservices architecture.
Below are key considerations to bear in mind when implementing a microservices architecture with Laravel.
Break Down the Application into Smaller Services
To initiate a microservices architecture, the initial action involves decomposing the application into smaller services, each tasked with a distinct business function or capability. Laravel offers a range of functionalities like routing, controllers, and middleware, which can be leveraged to craft these services.
Use APIs for Communication
Microservices interact with one another via APIs. Laravel provides several utilities like the Guzzle HTTP client for crafting and accessing APIs. Leveraging APIs enables each service to be developed and deployed autonomously, without dependencies on others.
Use a Service Registry
In a microservices architecture, services must be capable of discovering one another. This is typically achieved through a service registry, which maintains a record of the available services and their respective endpoints. Laravel offers native support for service discovery with integrations for popular service registries like Consul and Eureka.
Use a Message Broker for Asynchronous Communication
In certain scenarios, there arises a necessity for services to interact with one another asynchronously. To facilitate this, a message broker like RabbitMQ or Apache Kafka can be employed. Laravel offers seamless integrations with both RabbitMQ and Kafka for this purpose.
Use a Containerization Platform
Containerization platforms like Docker or Kubernetes are commonly employed for deploying and managing microservices. Laravel offers seamless integrations with both Docker and Kubernetes for streamlined deployment and management processes.
2) Laravel Serverless Architecture
In 2024, serverless architecture remains a prominent topic, poised to maintain its trendiness. Developers working with Laravel can capitalize on serverless technology to streamline application deployment and upkeep, resulting in significant time and cost savings.
Serverless architecture revolutionizes application development by eliminating the reliance on traditional servers. It allows developers to build and deploy applications without managing server infrastructure. Laravel, a popular PHP framework, can be leveraged to create serverless applications using cloud services such as AWS Lambda or Google Cloud Functions.
Ensure to consider these vital aspects when integrating a serverless architecture into Laravel:
Use a Function-as-a-Service Provider
To initiate the adoption of a serverless architecture, the primary task is selecting a function-as-a-service provider. Alternatives such as AWS Lambda, Google Cloud Functions, and Azure Functions Laravel offers integrations with these providers among others.
Break down the Application into Functions
In a serverless architecture, applications are decomposed into smaller functions, with each function assigned to a specific business function or capability. Laravel offers a range of functionalities, including routing and controllers, which can be leveraged to develop these functions from scratch.
Use Event-Driven Architecture
In a serverless architecture, functions are initiated by events. Laravel offers robust integration capabilities with various event-driven services, including AWS S3 and Google Cloud Pub/Sub, facilitating seamless interactions within applications. This facilitates the activation of functions through these services seamlessly.
Use a Database-as-a-Service Provider
In a serverless architecture, databases are commonly overseen by database-as-a-service (DBaaS) providers like AWS DynamoDB or Google Cloud Firestore. Laravel seamlessly integrates with various providers, including Azure Cosmos DB, enabling you to work with them effortlessly.
Use a Monitoring Tool
Monitoring the health and performance of serverless applications is crucial, just like any other application. Utilizing a monitoring tool like AWS CloudWatch or Google Cloud Monitoring allows tracking of function invocations, errors, and various metrics. Laravel offers integrations with these monitoring tools along with others like New Relic and Datadog.
Laravel Serverless Deployment Platform – Laravel Vapor
Laravel Vapor is a deployment platform designed specifically for hosting serverless Laravel applications.With Vapor, developers can effortlessly deploy their applications to AWS Lambda and efficiently manage infrastructure and scaling needs through a unified dashboard/
3) Real-time Applications
In 2024, the prominence of real-time applications is expected to rise, with Laravel's integration of websockets and event broadcasting offering developers the capability to craft interactive and dynamic real-time applications.
Real-time applications demand instantaneous updates to be readily visible to users. Laravel, a widely used PHP framework, offers numerous features and tools that can be harnessed to develop such applications.
Consider the following crucial factors when creating real-time applications in Laravel.
Use a Real-Time Communication Protocol
To begin developing real-time applications, the initial step involves selecting a suitable real-time communication protocol, such as WebSockets or Server-Sent Events (SSE). Laravel offers seamless integrations with various protocols including Pusher and Socket.io, alongside WebSockets and SSE.
Use a Real-Time Message Broker
Real-time applications facilitate the exchange of messages between clients and servers instantaneously. To manage these messages, real-time message brokers like Redis or RabbitMQ are often employed. Laravel offers seamless integrations with various message brokers, including Redis, RabbitMQ, and Kafka, allowing developers to efficiently handle real-time communication within their applications.
Use a Real-Time Event Broadcasting System
A real-time application sends events to clients instantly. Laravel offers an event broadcasting system to broadcast events to clients through WebSockets or SSE.
Use a Real-Time Notification System
In a real-time application, notifications are dispatched to clients in real-time. Laravel offers a notification system which can be utilized to send notifications to clients via WebSockets or (SSE).
Use a Real-Time Monitoring Tool
Monitoring the health and performance of real-time applications is crucial, much like any other application. Utilizing a real-time monitoring tool such as Laravel Horizon or Telescope enables the tracking of real-time events and metrics effectively.
4) Cloud-Native Applications
Cloud-native applications are anticipated to emerge as a significant trend in 2024. Developers working with Laravel have the opportunity to utilize cloud services provided by major platforms like AWS, Azure, and Google Cloud to create applications that are exceptionally scalable and resilient.
Cloud-native applications are specifically engineered to leverage the capabilities of cloud infrastructure, including scalability, flexibility, and reliability. Laravel, a popular PHP framework, is adept at crafting applications tailored for diverse cloud platforms, harnessing their inherent advantages.
Consider the following key elements when developing cloud-native applications with Laravel:
Use a Containerization Platform
When developing cloud-native applications, the initial stage involves utilizing a containerization platform, like Docker or Kubernetes. Laravel offers support for integration with these platforms, along with others such as Rancher.
Use a Cloud Platform
In a cloud-native application, the software operates within a cloud environment provided by platforms like Amazon Web Services (AWS), Google Cloud Platform (GCP), or Microsoft Azure. Laravel, a PHP framework, offers seamless integration with these leading cloud platforms, along with others like DigitalOcean, facilitating efficient deployment and management of applications.
Use a Cloud Database
In cloud-native applications, the database is commonly overseen by cloud-based database services like AWS RDS, GCP Cloud SQL, or Azure SQL. Laravel provides integrations with various services, including DigitalOcean Managed Databases, among others.
Use a Cloud Storage Service
Cloud-native applications typically rely on cloud storage services like AWS S3, GCP Cloud Storage, or Azure Blob Storage for managing storage. Laravel offers integrations with these services, along with others like DigitalOcean Spaces.
Use a Serverless Computing Service
Cloud-native applications leverage serverless computing services like AWS Lambda or GCP Cloud Functions to execute application code in a scalable and cost-efficient manner. Laravel offers integrations with these serverless platforms along with others like Azure Functions.
5) Laravel headless CMS Open-source
The rise of Laravel's Headless CMS architecture is increasingly recognized for its ability to decouple content management from presentation, offering developers enhanced flexibility and agility in application development.
Laravel offers a range of headless CMS solutions, including Strapi, Directus, and Contentful. These platforms empower developers to build dynamic and adaptable applications with ease.
Laravel Headless Ecommerce
As ecommerce continues to grow in popularity, developers proficient in Laravel are seeking headless CMS Ecommerce solutions that allow for the management of product catalogs and customer data without imposing restrictions on the front-end experience.
Laravel Forge provides developers with a smooth deployment process tailored for headless ecommerce content management systems (CMS), streamlining setup and facilitating rapid development.
Below is a list of popular open-source headless CMS options compatible with Laravel:
Strapi: The Best Headless CMS for Laravel
Strapi stands out as a robust open-source headless CMS, providing both a user-friendly interface and the flexibility to customize API endpoints.
Strapi enables developers to structure and manage content efficiently, providing APIs for content delivery. This feature makes it particularly attractive for Laravel developers seeking seamless content management. Moreover, Strapi offers a dedicated integration for Laravel, simplifying the process of incorporating Strapi into Laravel projects.
Strapi offers extensive customization capabilities, allowing users to incorporate custom code and plugins tailored to their project requirements.
Directus
Directus is an adaptable open-source headless CMS that empowers developers to design bespoke database schemas and API endpoints. With its intuitive interface, it facilitates seamless integration with various tools and platforms.
Cockpit
Cockpit stands out as a lightweight and open-source headless CMS, boasting a user-friendly interface that simplifies content management. With its support for custom fields, user roles, and permissions, Cockpit proves to be an ideal choice for efficiently managing content, particularly suited for smaller-scale projects.
Flamelink.io – A headless Firebase CMS
Flamelink is a cloud-based headless CMS renowned for its intuitive visual interface designed for content management. It seamlessly integrates with leading front-end frameworks such as React, Vue, and Angular. Boasting a comprehensive array of content management functionalities, Flamelink facilitates tasks such as localization and version control with ease.
Hygraph: The Next Generation GraphQL Content Platform
Hygraph is a cloud-based headless CMS offering a GraphQL API for content management and delivery. With features including schema validation and content localization, it provides seamless integrations with leading front-end frameworks such as React and Angular.
Various open-source headless CMS options offer Laravel developers a diverse range of choices for crafting bespoke front-end experiences without the limitations associated with conventional CMS platforms.
6) GraphQL API
GraphQL is a powerful query language designed for APIs, enabling developers to efficiently retrieve only the necessary data, thus minimizing network overhead and enhancing application performance. Laravel developers can take advantage of GraphQL to create APIs that are both efficient and flexible.
GraphQL is a query language for APIs known for its flexibility, efficiency, and power in data querying. It has gained significant traction within the developer community for its ability to efficiently handle complex queries and mutations. Laravel, a well-known PHP framework, offers developers the capability to construct GraphQL APIs proficient in managing intricate operations.
When integrating a GraphQL API into Laravel, it is crucial to consider the following key aspects:
Use a GraphQL Schema
To begin setting up a GraphQL API in Laravel, the initial task involves outlining a GraphQL schema to delineate the data types the API will deliver. Laravel boasts a convenient package known as GraphQL, facilitating the seamless definition and administration of a GraphQL schema.
Use a Resolver
In a GraphQL API, a resolver serves as a crucial component responsible for handling the resolution of queries or mutations to specific values. Laravel offers a user-friendly resolver system, empowering developers to define resolvers for individual fields within their GraphQL schema seamlessly.
Use a Data Source
In a GraphQL API, information is commonly sourced from various repositories, such as databases or external interfaces. Laravel facilitates connections with diverse data sources, including MySQL, MongoDB, and external APIs.
Use a Caching Mechanism
In a GraphQL API, caching serves to enhance performance by minimizing requests to the data source. Laravel provides seamless integrations with caching mechanisms such as Redis and Memcached. Leveraging these integrations can significantly enhance the efficiency of data caching within a GraphQL API.
Use a Security Mechanism
In a GraphQL API, ensuring security is paramount to safeguard against potential attacks and unauthorized access. Laravel offers seamless integrations with various security mechanisms, including JWT and OAuth, which can be effectively employed to fortify the security of a GraphQL API.
7) Artificial Intelligence and Machine Learning
Laravel developers have the chance to harness the power of AI and machine learning technologies to create smart applications capable of adapting to user behavior and preferences through learning mechanisms.
AI and Machine Learning are rapidly evolving disciplines that are transforming business operations. Utilizing Laravel, a popular PHP framework, offers avenues for developing AI and ML applications facilitating data analysis, predictive modeling, and task automation.
When integrating AI and ML capabilities into Laravel, it's vital to keep the following key considerations in mind:
Use a Data Pipeline
To initiate AI and ML integration within Laravel, the primary step involves establishing a data pipeline capable of gathering, refining, and analyzing data. Laravel facilitates seamless integration with various databases such as MySQL and PostgreSQL, alongside other tools for data processing like Apache Spark and Kafka.
Use a Machine Learning Library
In a machine learning application, a machine learning library is typically employed to construct and train models. Laravel offers integrations with various machine learning libraries, including TensorFlow and Scikit-learn, enabling developers to build and train models seamlessly within Laravel applications.
Use a Prediction System
In a machine learning application, a prediction system is employed to generate forecasts using a trained model. Laravel provides a user-friendly prediction system that allows for making predictions utilizing the trained model.
Use an Automation System
In an AI application, an automation system is utilized to streamline tasks through data analysis. Laravel offers a straightforward automation system, facilitating the automation of tasks based on analyzed data.
Use a Natural Language Processing (NLP) Library
In an AI application, text data analysis and processing rely on NLP (Natural Language Processing) libraries. Laravel facilitates integration with various NLP libraries, including SpaCy and NLTK, enabling developers to analyze and process text efficiently.
Use a Computer Vision Library
In an AI application, a computer vision library is employed to analyze and process image and video data. Laravel offers integrations with various computer vision libraries, including OpenCV and TensorFlow, enabling developers to leverage these tools for image and video data analysis and processing.
Conclusion
Laravel has gained widespread popularity among developers for web application development due to its combination of features. Its user-friendly nature, robust security measures, scalability, and vibrant community support have solidified its reputation as a dependable framework for crafting bespoke web applications.
0 notes
Text
Laravel Eloquent: Mastering the Art of Database Interactions
Laravel Eloquent is an Object-Relational Mapping (ORM) layer that comes built-in with the Laravel framework. It serves as an abstraction layer that allows developers to interact with databases using PHP objects and classes, rather than writing raw SQL queries. Eloquent simplifies the process of retrieving, inserting, updating, and deleting data from the database, making it more efficient and less error-prone.

One of the key features of Eloquent is its ability to represent database tables as models. Models are PHP classes that correspond to database tables, and each instance of a model represents a row in that table. Eloquent provides a set of methods and conventions that allow developers to define relationships between models, such as one-to-one, one-to-many, and many-to-many relationships.
Mastering the art of database interactions with Eloquent involves understanding the following concepts:
1. Model Definition: Creating models that correspond to database tables, defining table names, primary keys, and other properties.
2. Retrieving Data: Using Eloquent's query builder to fetch data from the database, including techniques like eager loading, chunking, and scoping.
3. Inserting and Updating Data: Creating new records, updating existing records, and handling mass assignment protection.
4. Relationships: Defining and working with one-to-one, one-to-many, and many-to-many relationships between models.
5. Eloquent Events: Handling events such as model creation, updating, and deleting, to perform additional logic or data manipulation.
6. Query Scopes: Defining reusable query constraints to simplify complex queries.
7. Accessors and Mutators: Customizing how Eloquent retrieves and stores data in the database, allowing for data transformation and formatting.
8. Eloquent Collections: Working with collections of models, and utilizing the collection's powerful methods for data manipulation and transformation.
9. Database Migrations: Using Laravel's migration system to create and manage database schema changes in a controlled and versioned manner.
10. Eloquent Serialization: Converting Eloquent models to and from various formats, such as JSON or arrays, for data transfer or storage.
By mastering these concepts, developers can leverage the power of Eloquent to build robust and scalable applications with efficient database interactions. Eloquent not only simplifies database operations but also promotes code organization, maintainability, and testability.
In Laravel, Eloquent models serve as the bridge between your application's logic and the underlying database. Each model corresponds to a specific database table, representing its structure and facilitating interactions with the records stored within that table.
Eloquent Model Structure
An Eloquent model is a PHP class that extends the base `Illuminate\Database\Eloquent\Model` class provided by Laravel. This base class provides a wide range of functionality for interacting with the database, including methods for creating, reading, updating, and deleting records.
Within an Eloquent model, you define the properties and relationships that correspond to the columns and associations of the respective database table. This includes specifying the table name, primary key, timestamps, and any additional attributes or behaviors specific to that model.
Defining Database Table Attributes
One of the primary responsibilities of an Eloquent model is to define the structure of the corresponding database table. This includes specifying the table name, primary key, and any other relevant attributes.
By default, Laravel follows a convention where the model name is singular, and the corresponding table name is the plural form of the model name. For example, a model named `User` would map to a table named `users`. However, you can override this convention by explicitly defining the table name within the model.
Models also define any timestamps columns (e.g., `created_at` and `updated_at`) and specify the primary key column if it differs from the default `id`.
Encapsulating Database Interactions
Eloquent models encapsulate all interactions with the database table they represent. This includes creating new records, retrieving existing records, updating records, and deleting records.
Instead of writing raw SQL queries, developers can leverage Eloquent's fluent interface, which provides a set of expressive methods for performing database operations. These methods allow you to build complex queries in a concise and readable manner, reducing the risk of SQL injection vulnerabilities and promoting code maintainability.
For example, to retrieve all records from a table, you can simply call the `all()` method on the corresponding model. To create a new record, you instantiate the model, set its properties, and call the `save()` method. Eloquent handles the underlying SQL statements and database interactions transparently.
Defining Model Relationships
Another crucial aspect of Eloquent models is the ability to define relationships between different database tables. Laravel supports various types of relationships, including one-to-one, one-to-many, and many-to-many.
By defining these relationships within the models, you can easily access and manipulate related data without writing complex join queries. Eloquent provides methods for eager loading related data, reducing the need for multiple database queries and improving performance.
Overall, Eloquent models serve as the backbone of database interactions in Laravel applications. They encapsulate the structure and behavior of database tables, facilitate database operations through a fluent interface, and enable the definition of relationships between tables. By leveraging Eloquent models, developers can write more maintainable and expressive code while reducing the risk of SQL injection vulnerabilities and promoting code organization.
CRUD (Create, Read, Update, Delete) operations are the fundamental actions that allow you to manage data in a database. Laravel's Eloquent ORM provides a set of methods that simplify these operations, making it easy to interact with database records without writing raw SQL queries.
Create
Eloquent provides several methods to create new records in the database. The most commonly used method is `create`, which accepts an array of key-value pairs representing the columns and their respective values. Eloquent handles the insertion of the new record into the database table.
Additionally, you can instantiate a new model instance, set its properties, and then call the `save` method to persist the record in the database.
Read
Retrieving data from the database is a common operation, and Eloquent offers a variety of methods to fetch records. The `all` method retrieves all records from the database table associated with the model. You can also use the `find` method to retrieve a single record by its primary key value.
Eloquent allows you to build complex queries using its fluent query builder, enabling you to filter, sort, and apply constraints to the retrieved data based on your application's requirements.
Update
Updating existing records in the database is straightforward with Eloquent. You can retrieve an existing record using methods like `find` or `findOrFail`, modify its properties, and then call the `save` method to persist the changes to the database.
Alternatively, you can use the `update` method to update one or more records in the database based on specific conditions. This method accepts an array of key-value pairs representing the columns and their new values, along with a condition specifying which records should be updated.
Delete
Deleting records from the database is handled by the `delete` method in Eloquent. You can retrieve a specific record using methods like `find` or `findOrFail` and then call the `delete` method on that instance to remove it from the database.
Eloquent also provides the `destroy` method, which allows you to delete one or more records based on their primary key values or specific conditions.
In addition to these fundamental CRUD operations, Eloquent offers several other methods and features that enhance database interactions. These include:
1. Relationships: Eloquent allows you to define and work with relationships between models, such as one-to-one, one-to-many, and many-to-many relationships, simplifying the retrieval and manipulation of related data.
2. Accessors and Mutators: These allow you to customize how Eloquent retrieves and stores data in the database, enabling data transformation and formatting.
3. Scopes: Scopes provide a way to define reusable query constraints, making it easier to build complex queries across your application.
4. Events: Eloquent provides a set of events that you can hook into, allowing you to perform additional logic or data manipulation before or after various database operations.
By leveraging Eloquent's methods and features for CRUD operations, developers can write more concise and expressive code while reducing the risk of SQL injection vulnerabilities and promoting code maintainability.
In relational databases, tables often have relationships with one another. For example, a blog post may have many comments, or a user may have multiple addresses. Laravel's Eloquent ORM provides a convenient way to define and work with these relationships between models, making it easier to retrieve and manipulate related data.
One-to-One Relationships
A one-to-one relationship is a type of relationship where one record in a table is associated with a single record in another table. For example, a `User` model might have a one-to-one relationship with an `Address` model, where each user has a single address associated with them.
In Eloquent, you can define a one-to-one relationship using methods like `hasOne` and `belongsTo`. These methods allow you to specify the related model and the foreign key column that links the two tables together.
One-to-Many Relationships
A one-to-many relationship is a type of relationship where a single record in one table can be associated with multiple records in another table. For example, a `User` model might have a one-to-many relationship with a `Post` model, where each user can have multiple blog posts.
Eloquent provides methods like `hasMany` and `belongsTo` to define one-to-many relationships. The `hasMany` method is used on the parent model (e.g., `User`), while the `belongsTo` method is used on the child model (e.g., `Post`).
Many-to-Many Relationships
A many-to-many relationship is a type of relationship where multiple records in one table can be associated with multiple records in another table. For example, a `User` model might have a many-to-many relationship with a `Role` model, where a user can have multiple roles, and a role can be assigned to multiple users.
In Eloquent, many-to-many relationships are defined using methods like `belongsToMany` on both models involved in the relationship. Additionally, you need to specify an intermediate table (often called a pivot table) that stores the mapping between the two models.
Defining Relationships
Relationships in Eloquent are typically defined within the model classes themselves. For example, in a `User` model, you might define a one-to-many relationship with the `Post` model like this:
```php
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
```
And in the `Post` model, you would define the inverse relationship:
```php
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
```
Working with Relationships
Once you have defined the relationships between your models, Eloquent provides several methods to interact with related data. For example, you can retrieve a user's posts like this:
```php
$user = User::findOrFail(1);
$posts = $user->posts;
```
You can also create new related records, update existing related records, and remove related records using Eloquent's relationship methods.
Eloquent relationships make it easier to work with related data in your application, reducing the need for complex join queries and promoting code organization and maintainability.
Query Scopes are a powerful feature in Eloquent that allow developers to encapsulate and reuse common query constraints or modifications. They provide a way to define reusable query logic that can be easily applied to Eloquent queries, enhancing code readability, maintainability, and reducing duplication.
What are Query Scopes?
Query Scopes are essentially methods defined within an Eloquent model that add additional constraints or modifications to the query builder instance. These methods can be chained together with other Eloquent query builder methods, allowing for the creation of complex and expressive queries.
There are two types of Query Scopes in Eloquent:
1. Local Scopes: These are scopes defined within a specific Eloquent model and can only be used with that model.
2. Global Scopes: These are scopes that are applied to all queries for a given model, regardless of where the query is constructed.
Benefits of Query Scopes
Query Scopes provide several benefits that enhance the development experience and code quality:
1. Reusability: By encapsulating common query logic into scopes, developers can easily reuse these scopes across different parts of their application, reducing code duplication.
2. Readability: Well-named scopes make queries more self-documenting and easier to understand, improving code readability and maintainability.
3. Testability: Since scopes are defined as methods within the Eloquent model, they can be easily unit tested, ensuring the correctness of the query logic.
4. Abstraction: Scopes abstract away complex query logic, allowing developers to focus on the higher-level application logic.
Using Query Scopes
To define a local scope, you create a method within your Eloquent model that returns an instance of the query builder with the desired constraints or modifications applied. For example, you might define a scope to retrieve only active users like this:
```php
class User extends Model
{
public function scopeActive($query)
{
return $query->where('active', true);
}
}
```
You can then use this scope when querying for users:
```php
$activeUsers = User::active()->get();
```
Global scopes, on the other hand, are defined using the `addGlobalScope` method within the `boot` method of your Eloquent model. These scopes are automatically applied to all queries for that model.
```php
class User extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope('active', function ($query) {
$query->where('active', true);
});
}
}
```
In addition to defining custom scopes, Eloquent also provides several built-in scopes, such as `whereKey`, `whereKeyNot`, and `latest`, among others.
By leveraging Query Scopes, developers can create more readable, maintainable, and testable code while reducing duplication and promoting code organization within their Laravel applications.
In Laravel, when you retrieve data from the database using Eloquent, the results are returned as instances of the `Illuminate\Database\Eloquent\Collection` class. Eloquent Collections are powerful data structures that provide a rich set of methods for working with and manipulating the retrieved data.
What are Eloquent Collections?
Eloquent Collections are Laravel's implementation of the collection data structure, designed to store and manipulate collections of related objects or items, such as Eloquent models or arrays. They serve as a wrapper around the underlying data, providing a consistent and intuitive interface for interacting with that data.
Benefits of Eloquent Collections
Working with Eloquent Collections offers several advantages:
1. Fluent Interface: Collections provide a fluent interface with a wide range of methods for manipulating and transforming data, making it easy to chain multiple operations together.
2. Immutable Data: Collections are immutable, meaning that when you perform an operation on a collection, a new instance is returned, leaving the original collection unchanged. This helps prevent unintended side effects and promotes functional programming patterns.
3. Lazy Loading: Collections support lazy loading, which means that data transformations or operations are not applied until the collection is actually used or iterated over. This can lead to significant performance improvements, especially when working with large datasets.
4. Type Safety: Collections enforce type safety, ensuring that only objects of the same type are stored and manipulated within a given collection.
5. Consistency: Eloquent Collections provide a consistent interface for working with data, regardless of the source (e.g., database queries, arrays, or other collections).
Working with Eloquent Collections
Eloquent Collections offer a wide range of methods for manipulating and transforming data. Here are some common operations you can perform on collections:
Filtering: You can use methods like `filter`, `where`, `reject`, and `whereIn` to filter the items in a collection based on specific conditions or criteria.
Mapping and Transforming: Methods like `map`, `transform`, `flatMap`, and `flatten` allow you to apply transformations or operations to each item in the collection, returning a new collection with the transformed data.
Reducing and Aggregating: You can use methods like `reduce`, `sum`, `avg`, and `max` to perform aggregations or reductions on the data in the collection.
Sorting and Reordering: Collections provide methods like `sort`, `sortBy`, and `sortByDesc` for sorting and reordering the items based on specific criteria.
Retrieving and Checking: Methods like `first`, `last`, `contains`, and `isEmpty` allow you to retrieve specific items or check for the existence of items in the collection.
Eloquent Collections also integrate seamlessly with other Laravel features, such as pagination and caching, making it easier to work with large datasets and improve application performance.
By leveraging the power of Eloquent Collections, developers can write more expressive and maintainable code for manipulating and transforming data retrieved from the database, further enhancing the productivity and effectiveness of working with Laravel's Eloquent ORM.
Conclusion:
Laravel Eloquent empowers developers to master the art of database interactions by offering a clean, expressive syntax for working with databases. Its features, from simple CRUD operations to advanced relationships and query scopes, enable developers to build scalable and maintainable applications without sacrificing readability. Eloquent Collections, a powerful data structure, provide a rich set of methods for working with and manipulating retrieved data, making expertise in Collections highly valuable when looking to hire Laravel developers or partnering with a Laravel development company. By embracing Eloquent, Laravel developers can streamline their workflow, focus on creating innovative solutions, and make the database interaction process a joy rather than a challenge, ultimately delivering high-quality, efficient applications.
0 notes
Text
Laravel Collection Sort By Value With Example
Laravel Collection Sort By Value With Example
Hello buddy, in this article, we will learn about how to sort data in laravel collection, I will show you the easiest way to sort the laravel collection. I will give you a list of examples of sort by collection in laravel. so you can easily use it with your laravel 5, laravel 6, laravel 7 and laravel 8 application. so let’s see the below example that will help you a lot. We will see below…

View On WordPress
#laravel collection group by#laravel collection sort by date desc#laravel collection sort by desc#laravel collection sort by key#laravel collection sort by multiple columns#laravel collection sort by value#laravel collection sortby multiple#laravel collection to array of objects#laravel collection->sort by desc#laravel collection->sort by key#laravel collection->sort by value#laravel collection->sortby multiple
1 note
·
View note
Link
Nuxt.js provides an Axios module for easy integration with your application. Axios is a promise-based HTTP client that works in the browser and Node.js environment or, in simpler terms, it is a tool for making requests (e.g API calls) in client-side applications and Node.js environment. In this tutorial, we’re going to learn how to use the Axios module and how to make a request on the server-side using asyncData and fetch. These two methods make a request on the server-side but they have some differences which we’re also going to cover. Finally, we’ll learn how to perform authentication and secure pages/routes using the auth module and auth middleware. This article requires basic knowledge of Nuxtjs and Vuejs as we’ll be building on top of that. For those without experience with Vuejs, I recommend you start from their official documentation and the Nuxt official page before continuing with this article.
What Is The Nuxt.js Axios Module?
According to the official Documentation,
“It is a Secure and easy Axios integration with Nuxt.js.”
Here are some of its features:
Automatically set base URL for client-side & server-side.
Proxy request headers in SSR (Useful for auth).
Fetch Style requests.
Integrated with Nuxt.js Progressbar while making requests.
To use the axios module in your application, you will have to first install it by using either npm or yarn. YARN
yarn add @nuxtjs/axios
NPM
npm install @nuxtjs/axios
Add it into your nuxt.config.js file:
modules: [ '@nuxtjs/axios', ], axios: { // extra config e.g // BaseURL: 'https://link-to-API' }
The modules array accepts a list of Nuxt.js modules such as dotenv, auth and in this case, Axios. What we’ve done is to inform our application that we would be using the Axios module, which we reference using @nuxtjs/axios. This is then followed by the axios property which is an object of configurations like the baseURL for both client-side and server-side. Now, you can access Axios from anywhere in your application by calling this.$axios.method or this.$axios.$method. Where method can be get, post, or delete.
Making Your First Request Using Axios
For this tutorial, I’ve put together a simple application on Github. The repository contains two folders, start and finish, the start folder contains all you need to get right into the tutorial. The finish folder contains a completed version of what we would be building. After cloning the repo and opening the start folder, we would need to install all our packages in the package.json file so open your terminal and run the following command:
npm install
Once that is done, we can start our app using the npm run dev command. This is what you should see when you go to localhost:3000.
Our application’s landing page. (Large preview)
The next thing we have to do is to create a .env file in the root folder of our application and add our API URL to it. For this tutorial, we’ll be using a sample API built to collect reports from users.
API_URL=https://ireporter-endpoint.herokuapp.com/api/v2/
This way, we do not have to hard code our API into our app which is useful for working with two APIs (development and production). The next step would be to open our nuxt.config.js file and add the environmental variable to our axios config that we added above.
/* ** Axios module configuration */ axios: { // See https://github.com/nuxt-community/axios-module#options baseURL: process.env.API_URL, },
Here, we tell Nuxt.js to use this baseURL for both our client-side and server-side requests whenever we use this Axios module. Now, to fetch a list of reports, let us open the index.vue file and add the following method to the script section.
async getIncidents() { let res = await this.$store.dispatch("getIncidents"); this.incidents = res.data.data.incidents; }
What we have done is to create an async function that we call getIncidents() and we can tell what it does from the name — it fetches a list of incidents using the Vuex store action method this.$store.dispatch. We assign the response from this action to our incidents property so we can be able to make use of it in the component. We want to call the getIncidents() method whenever the component mounts. We can do that using the mounted hook.
mounted() { this.getIncidents() }
mounted() is a lifecycle hook that gets called when the component mounts. That will cause the call to the API to happen when the component mounts. Now, let us go into our index.js file in our store and create this action where we’ll be making our Axios request from.
export const actions = { async getIncidents() { let res = await this.$axios.get('/incidents') return res; } }
Here, we created the action called getIncidents which is an async function, then we await a response from the server and return this response. The response from this action is sent back to our getIncidents() method in our index.vue file. If we refresh our application, we should now be able to see a long list of incidents rendered on the page.

List of incidents on landing page. (Large preview)
We have made our first request using Axios but we won’t stop there, we are going to be trying out asyncData and fetch to see the differences between them and using Axios.
AsyncData
AsyncData fetches data on the server-side and it’s called before loading the page component. It does not have access to this because it is called before your page component data is created. this is only available after the created hook has been called so Nuxt.js automatically merges the returned data into the component’s data. Using asyncData is good for SEO because it fetches your site’s content on the server-side and also helps in loading content faster. Note that asyncData method can only be used in the pages folder of your application as it would not work in the components folder. This is because asyncData hook gets called before your component is created.
Image from Nuxt blog. (Large preview)
Let us add asyncData to our index.vue file and observe how fast our incidents data loads. Add the following code after our components property and let us get rid of our mounted hook.
async asyncData({ $axios }) { let { data } = await $axios.get("/incidents"); return { incidents: data.data.incidents }; }, // mounted() { // this.getIncidents(); // },
Here, the asyncData method accepts a property from the context $axios. We use this property to fetch the list of incidents and the value is then returned. This value is automatically injected into our component. Now, you can notice how fast your content loads if you refresh the page and at no time is there no incident to render.
Fetch
The Fetch method is also used to make requests on the server-side. It is called after the created hook in the life cycle which means it has access to the component’s data. Unlike the asyncData method, the fetch method can be used in all .vue files and be used with the Vuex store. This means that if you have the following in your data function.
data() { return { incidents: [], id: 5, gender: 'male' }; }
You can easily modify id or gender by calling this.id or this.gender.
Using Axios As A Plugin
During the process of development with Axios, you might find that you need extra configuration like creating instances and interceptors for your request so your application can work as intended and thankfully, we can do that by extending our Axios into a plugin. To extend axios, you have to create a plugin (e.g. axios.js) in your plugins folder.
export default function ({ $axios, store, redirect }) { $axios.onError(error => { if (error.response && error.response.status === 500) { redirect('/login') } }) $axios.interceptors.response.use( response => { if (response.status === 200) { if (response.request.responseURL && response.request.responseURL.includes('login')) { store.dispatch("setUser", response); } } return response } ) }
This is an example of a plugin I wrote for a Nuxt application. Here, your function takes in a context object of $axios, store and redirect which we would use in configuring the plugin. The first thing we do is to listen for an error with a status of 500 using $axios.onError and redirect the user to the login page. We also have an interceptor that intercepts every request response we make in our application checks if the status of the response we get is 200. If that is true we proceed and check that there is a response.request.responseURL and if it includes login. If this checks out to be true, we then send this response using our store’s dispatch method where it then mutated in our state. Add this plugin to your nuxt.config.js file:
plugins: [ '~/plugins/axios' ]
After doing this, your Axios plugin would intercept any request you make and check if you have defined a special case for it.
Introduction To The Auth Module
The auth module is used for performing authentication for your Nuxt application and can be accessed from anywhere in your application using $this.auth. It is also available in fetch, asyncData, middleware and NuxtInitServer from the context object as $auth. The context provides additional objects/params from Nuxt to Vue components and is available in special nuxt lifecycle areas like those mentioned above. To use the auth module in your application, you would have to install it using yarn or npm. YARN
yarn add @nuxtjs/auth
NPM
npm install @nuxtjs/auth
Add it to your nuxt.config.js file.
modules: [ '@nuxtjs/auth' ], auth: { // Options }
The auth property accepts a list of properties such as strategies and redirect. Here, strategies accepts your preferred authentication method which can be:
local For username/email and password-based flow.
facebook For using Facebook accounts as a means of authentication.
Github For authenticating users with Github accounts.
Google For authenticating users with Google accounts.
Auth0
Laravel Passport
The redirect property accepts an object of links for:
login Users would be redirected to this link if login is required.
logout Users would be redirected here if after logout current route is protected.
home Users would be redirected here after login.
Now, let us add the following to our nuxt.config.js file.
/* ** Auth module configuration */ auth: { redirect: { login: '/login', logout: '/', home: '/my-reports' }, strategies: { local: { endpoints: { login: { url: "/user/login", method: "post", propertyName: "data.token", }, logout: false, user: false, }, tokenType: '', tokenName: 'x-auth', autoFetchUser: false }, }, }
Please note that the auth method works best when there is a user endpoint provided in the option above. Inside the auth config object, we have a redirect option in which we set our login route to /login, logout route to / and home route to /my-reports which would all behave as expected. We also have a tokenType property which represents the Authorization type in the header of our Axios request. It is set to Bearer by default and can be changed to work with your API. For our API, there is no token type and this is why we’re going to leave it as an empty string. The tokenName represents the Authorization name (or the header property you want to attach your token to) inside your header in your Axios request. By default, it is set to Authorization but for our API, the Authorization name is x-auth. The autoFetchUser property is used to enable user fetch object using the user endpoint property after login. It is true by default but our API does not have a user endpoint so we have set that to false. For this tutorial, we would be using the local strategy. In our strategies, we have the local option with endpoints for login, user and logout but in our case, we would only use the *login* option because our demo API does not have a *logout* endpoint and our user object is being returned when *login* is successful. Note: The auth module does not have a register endpoint option so that means we’re going to register the traditional way and redirect the user to the login page where we will perform the authentication using this.$auth.loginWith. This is the method used in authenticating your users. It accepts a ‘strategy’ (e.g local) as a first argument and then an object to perform this authentication with. Take a look at the following example.
let data { email: '[email protected]', password: '123456' } this.$auth.loginWith('local', { data })
Using The Auth Module
Now that we have configured our auth module, we can proceed to our registration page. If you visit the /register page, you should see a registration form.
Register page. (Large preview)
Let us make this form functional by adding the following code:
methods: { async registerUser() { this.loading = true; let data = this.register; try { await this.$axios.post("/user/create", data); this.$router.push("/login"); this.loading = false; this.$notify({ group: "success", title: "Success!", text: "Account created successfully" }); } catch (error) { this.loading = false; this.$notify({ group: "error", title: "Error!", text: error.response ? error.response.data.error : "Sorry an error occured, check your internet" }); } } }
Here, we have an async function called registerUser which is tied to a click event in our template and makes an Axios request wrapped in a try/catch block to an endpoint /user/create. This redirects to the /login page and notifies the user of a successful registration. We also have a catch block that alerts the user of any error if the request is not successful. If the registration is successful, you would be redirected to the login page.
Login page with notification component. (Large preview)
Here, we’re going to make use of auth authentication method this.$auth.loginWith('local', loginData) after which we would use the this.$auth.setUser(userObj) to set the user in our auth instance. To get the login page working, let’s add the following code to our login.vue file.
methods: { async logIn() { let data = this.login; this.loading = true; try { let res = await this.$auth.loginWith("local", { data }); this.loading = false; let user = res.data.data.user; this.$auth.setUser(user); this.$notify({ group: "success", title: "Success!", text: "Welcome!" }); } catch (error) { this.loading = false; this.$notify({ group: "error", title: "Error!", text: error.response ? error.response.data.error : "Sorry an error occured, check your internet" }); } } }
We created an async function called logIn using the auth method this.$auth.loginWith('local, loginData). If this login attempt is successful, we then assign the user data to our auth instance using this.$auth.setUser(userInfo) and redirect the user to the /my-report page. You can now get user data using this.$auth.user or with Vuex using this.$store.state.auth.user but that’s not all. The auth instance contains some other properties which you can see if you log in or check your state using your Vue dev tools. If you log this.$store.state.auth to the console, you’ll see this:
{ "auth": { "user": { "id": "d7a5efdf-0c29-48aa-9255-be818301d602", "email": "[email protected]", "lastName": "Xo", "firstName": "Tm", "othernames": null, "isAdmin": false, "phoneNumber": null, "username": null }, "loggedIn": true, "strategy": "local", "busy": false } }
The auth instance contains a loggedIn property that is useful in switching between authenticated links in the nav/header section of your application. It also contains a strategy method that states the type of strategy the instance is running (e.g local). Now, we will make use of this loggedIn property to arrange our nav links. Update your navBar component to the following:
<template> <header class="header"> <div class="logo"> <nuxt-link to="/"> <Logo /> </nuxt-link> </div> <nav class="nav"> <div class="nav__user" v-if="auth.loggedIn"> <p></p> <button class="nav__link nav__link--long"> <nuxt-link to="/report-incident">Report incident</nuxt-link> </button> <button class="nav__link nav__link--long"> <nuxt-link to="/my-reports">My Reports</nuxt-link> </button> <button class="nav__link" @click.prevent="logOut">Log out</button> </div> <button class="nav__link" v-if="!auth.loggedIn"> <nuxt-link to="/login">Login</nuxt-link> </button> <button class="nav__link" v-if="!auth.loggedIn"> <nuxt-link to="/register">Register</nuxt-link> </button> </nav> </header> </template> <script> import { mapState } from "vuex"; import Logo from "@/components/Logo"; export default { name: "nav-bar", data() { return {}; }, computed: { ...mapState(["auth"]) }, methods: { logOut() { this.$store.dispatch("logOut"); this.$router.push("/login"); } }, components: { Logo } }; </script> <style></style>
In our template section, we have several links to different parts of the application in which we are now using auth.loggedIn to display the appropriate links depending on the authentication status. We have a logout button that has a click event with a logOut() function attached to it. We also display the user’s email gotten from the auth property which is accessed from our Vuex store using the mapState method which maps our state auth to the computed property of the nav component. We also have a logout method that calls our Vuex action logOut and redirects the user to the login page. Now, let us go ahead and update our store to have a logOut action.
export const actions = { // .... logOut() { this.$auth.logout(); } }
The logOut action calls the auth logout method which clears user data, deletes tokens from localStorage and sets loggedIn to false. Routes like /my-reports and report-incident should not be visible to guests but at this point in our app, that is not the case. Nuxt does not have a navigation guard that can protect your routes, but it has is the auth middleware. It gives you the freedom to create your own middleware so you can configure it to work the way you want. It can be set in two ways:
Per route.
Globally for the whole app in your nuxt.config.js file.
router: { middleware: ['auth'] }
This auth middleware works with your auth instance so you do not need to create an auth.js file in your middleware folder. Let us now add this middleware to our my-reports.vue and report-incident.vue files. Add the following lines of code to the script section of each file.
middleware: 'auth'
Now, our application would check if the user trying to access these routes has an auth.loggedIn value of true. It’ll redirect them to the login page using our redirect option in our auth config file — if you’re not logged in and you try to visit either /my-report or report-incident, you would be redirected to /login. If you go to /report-incidents, this is what you should see.
Report incident page. (Large preview)
This page is for adding incidents but that right now the form does not send incident to our server because we are not making the call to the server when the user attempts to submit the form. To solve this, we will add a reportIncident method which will be called when the user clicks on Report. We’ll have this in the script section of the component. This method will send the form data to the server. Update your report-incident.vue file with the following:
<template> <section class="report"> <h1 class="report__heading">Report an Incident</h1> <form class="report__form"> <div class="input__container"> <label for="title" class="input__label">Title</label> <input type="text" name="title" id="title" v-model="incident.title" class="input__field" required /> </div> <div class="input__container"> <label for="location" class="input__label">Location</label> <input type="text" name="location" id="location" v-model="incident.location" required class="input__field" /> </div> <div class="input__container"> <label for="comment" class="input__label">Comment</label> <textarea name="comment" id="comment" v-model="incident.comment" class="input__area" cols="30" rows="10" required ></textarea> </div> <input type="submit" value="Report" class="input__button" @click.prevent="reportIncident" /> <p class="loading__indicator" v-if="loading">Please wait....</p> </form> </section> </template> <script> export default { name: "report-incident", middleware: "auth", data() { return { loading: false, incident: { type: "red-flag", title: "", location: "", comment: "" } }; }, methods: { async reportIncident() { let data = this.incident; let formData = new FormData(); formData.append("title", data.title); formData.append("type", data.type); formData.append("location", data.location); formData.append("comment", data.comment); this.loading = true; try { let res = await this.$store.dispatch("reportIncident", formData); this.$notify({ group: "success", title: "Success", text: "Incident reported successfully!" }); this.loading = false; this.$router.push("/my-reports"); } catch (error) { this.loading = false; this.$notify({ group: "error", title: "Error!", text: error.response ? error.response.data.error : "Sorry an error occured, check your internet" }); } } } }; </script> <style> </style>
Here, we have a form with input fields for title, location, and comment with two-way data binding using v-model. We also have a submit button with a click event. In the script section, we have a reportIncident method that collects all the information provided in the form and is sent to our server using FormData because the API is designed to also accept images and videos. This formData is attached to a Vuex action using the dispatch method, if the request is successful, you get redirected to /my-reports with a notification informing you that this request was successful otherwise, you would be notified of an error with the error message. At this point, we don’t have reportIncident action in our store yet so in your browser console, you would see an error if you try to click submit on this page.

Vuex error message. (Large preview)
To fix this, add the reportIncident action your index.js file.
export const actions = { // ... async reportIncident({}, data) { let res = await this.$axios.post('/incident/create', data) return res; } }
Here, we have a reportIncident function that takes in an empty context object and the data we’re sending from our form. This data is then attached to a post request that creates an incident and returns back to our report-incident.vue file. At this point, you should be able to add a report using the form after which you would be redirected to /my-reports page.
My reports page empty. (Large preview)
This page should display a list of incidents created by the user but right now it only shows what we see above, let’s go ahead to fix that. We’re going to be using the fetch method we learned about to get this list. Update your my-reports.vue file with the following:
<script> import incidentCard from "@/components/incidentCard.vue"; export default { middleware: "auth", name: "my-reports", data() { return { incidents: [] }; }, components: { incidentCard }, async fetch() { let { data } = await this.$axios.get("/user/incidents"); this.incidents = data.data; } }; </script>
Here, we use fetch method to get user-specific incidents and assign the response to our incidents array. If you refresh your page after adding an incident, you should see something like this.
My Reports page with a report. (Large preview)
At this point, we would notice a difference in how fetch method and asyncData loads our data.
Conclusion
So far, we have learned about the Axios module and all of its features. We have also learned more about asyncData, and how we can fetch both of them together despite their differences. We’ve also learned how to perform authentication in our application using the auth module and how to use the auth middleware to protect our routes. Here are some useful resources that talk more about all we’ve covered.
Getting started with meta tags in Nuxjs.
Using the dotenv module in Nuxt.
Using Fetch in your Nuxt app.
Getting started with asyncData.
0 notes
Text
25 Best PHP Frameworks for Web Development in 2020
PHP as a server-side programming language has discerned remarkable growth in the last few years.
The major reason for the is application built using PHP frameworks is highly responsive and well-defined to fulfilling the distinct business requirements.
The W3Techs survey states that 82% of the majority web server uses PHP as their development tool.
It is obvious to ask why PHP is so popular. Here are some reasons:
It provides great HTML and database integration support.
Interactive features with other tools
It is a language that is easy to learn in a short period.
PHP help developers more than one way to promote the rapid application development, from the design structures, providing the building blocks of them.
Here are the best and top 25 PHP frameworks in the market which fluctuate with multiple and varied priorities in terms of performance and the list of built-in functions among other examples.
Go through this list to choose the framework that works best for you to get your website developed.
Reason to Choose PHP Framework
PHP provides huge benefits for both developers and business owners in terms of easy development, scalability, and security. Here are some more benefits of using PHP as a developing tool.
It is a well-designed PHP framework so, it helps you in implementing common problems.
Since it is an open-source community that provides you with an application architecture to guide your development.
As we mentioned above, they make you more secure for your application.
Each PHP solution that presents in modern PHP frameworks are continuously tested.
Additionally, they are peer-reviewed and validated by multiple developers using the framework.
Security issues and other problems that you might face in your established code get quickly noticed and fixed since it is an open-source framework.
You can develop codes that are loosely coupled. This leads to easy in reading, testing, maintaining, and developing further.
Ways to choose a PHP framework
There are many PHP frameworks are available, but you need to pick framework which suits on your application and business requirements.
Answer the below few questions to choose a PHP framework according to your needs:
What are the features and functionality that you need in the framework?
Which learning curve of the framework will help your application development more?
How scalable is the framework for your application?
Is the framework actively developed and maintained by the core team?
Do you want the framework to provide long-term support?
Does the framework have strong community support to help you with development?
Once you arrive answer for your above question analysis the different frameworks that are available in market to decide on which PHP framework to use for your project.
Here are the top 25 frameworks that are available in the market.
1. Laravel PHP Framework
It is developed in 2011 by Taylor Otwell which is a free open-source framework.
One the most popular PHP frameworks, Laravel is used in the development of web apps while following the model-view-controller (MVC) architectural pattern and based on Symphony.
You can learn it easily since every Laravel release is elaborate which makes much more easy to continuously updating their knowledge base.
It is mostly suitable for rapid application development. The framework has a well-built templating engine that enables a wide array of common tasks — like identification, caching, user management, and RESTful routing — easier for software developers.
Refined syntax, the ability to asynchronously run tasks in the background to improve performance. It is well-established integration with Amazon Web Services (AWS) add to the list of features that make Laravel one of the best PHP frameworks.
Laravel provides incredible features as well as extensive community support. If you want to develop an application on the Laravel PHP framework you can hire our Laravel developers who are expert in handling complex tasks easily and deliver you a unique web application.
Features
Built-in Authorization & Authentication System for easy verification
Integration with Cached Memory for better execution
Effortless Exception & Configuration error handling
Resolving attitude towards common Technical Vulnerabilities
Segregation of business logic code from Presentation Logic
Flawless Database Migration: Syncing the database between the development machines is a quite tedious yet important aspect for developers.
2. Symfony
The Symphony best PHP frameworks year after year, and there are many reasons for it.
It is developed in 2015 with in-built testing functionality and features of offering developers reusable components and code.
It is mostly used by large organizations and big enterprise software development efforts.
It also facilitates the developers to use several OF Symfony’s components — or all of them at once, depending on the project needs.
As Symphony’s vast ecosystem is continuously supported by a community of developers, the framework offers comprehensive technical documentation. The learning curve is rather steep, so those unfamiliar with the framework would need time and effort to grasp it. If your solutions will rely on modular, Symphony is the top option.
Features
This is the best choice for businesses. It is fast and takes fewer system resources.
is considered to simplify development tasks as it does not demand extensive code to write for creating web applications.
It provides stable, faster and more flexible web application development.
Symfony flexibility to create great applications with high-performance rate.
The major advantage of this framework is that it consumes less memory than others.
Developers are allowed to create web applications at a significant speed in this framework.
It is fully adaptable to the unique requirements of developers as it is available with fully configurable and independent elements.
3.Codelgniter
CodeIgniter makes use of Model View Controller (MVC) architecture for development.
It is meant for using different components to handle specific development tasks. Due to this it gains developers strength.
It also enables you to build highly-scalable web applications with a smaller footprint.
If you are new to PHP frameworks, CodeIgniter can be an excellent choice, because it is rather easy to learn and get started with. Plus, the platform boasts excellent documentation, which means you should not have too much trouble learning the basics.
CodeIgniter is popular for creating lightweight applications that run well on modest servers which offers solid performance.
Features:
It offers high-performance and uses a lightweight framework.
Get started quickly, thanks to the framework’s simplicity and excellent documentation.
Create scalable apps using the framework’s MVC-based architecture.
4. Cake PHP
CakePHP uses MVC and it is the first framework based on MVC to hit the market.
It is mostly popular for high performance and is used by many organizations. It improved a lot by adding new components and increasing performance.
Its a way of approaching convention in coding makes it more reliable for developers to choose it.
If you have master its set of conventions, you can focus on development and get more work done faster.
You can include a substantial amount of helpful components (as every PHP framework should) using a wonderful set of libraries offered by this framework.
During our tests, we found that CakePHP offers one of the most thorough sets of components you can find, so it’s a great option if you need to implement hard-to-find features.
Features:
Take advantage of a broad set of components
Use CakePHP’s conventions to code projects faster
5. Zend Framework (Laminas)
60+ packages for professional PHP development is collected under an Zend Framework. We can also state its collection of these packages.
During the development period, you to focus only on the components and functions you want, and ignore everything else in the Zend framework.
It also facilitates to reuse a substantial amount of the code you write with its object-oriented nature, which is always great news.
Zend Framework is now the Laminas Project.
Features:
Zend enables us to use a PHP object-oriented framework with an MVC architecture.
Re-use your code thanks to the platform’s design.
Integrate Zend with external libraries easily.
Use only the components you want, and ignore everything else.
6. Phalcon
Phalcon is a bit of irregularity when it comes to PHP frameworks. Its source code is written in C, so it is a C extension of PHP.
It may appear as odd in this digital environment.
But, guess it is the fastest framework we've had the satisfaction of using.
It is known for it consistently delivering results that are near the top of the pack at good content (current result).
It uses MVC architecture and also very light on resources.
Plus, it’s unique in that the framework itself has almost no files once you install it. Instead, you just add the modules and libraries you need when you need them, which makes for a very uncluttered php development process.
Features:
Use a PHP framework that is based on C.
Take advantage of Phalcon’s fantastic performance and low resource overhead.
Use only the modules and libraries you need.
7. Slim
Have you heard about a micro framework, don't think it offers fewer features but lightweight framework.
It is one of the micro-framework that allows quickly creating easy and powerful web applications as well as APIs.
It has a reliable router, template depiction with bespoke views, HTTP caching, flash messages, protected cookies with AES-256 encryption, logging with custom log writers, error treatment and debugging and uncomplicated configuration.
Features
It offers fast and powerful routing based on HTTP which useful for designing SEO-friendly URLs.
It uses less cache since HTTP caching is used for website performance.
Slim has a high concentration on the security of the application, so it uses Secured cookies for improving the security of the system.
It uses Dependency injection for controlling external tools that are needed for application.
8. Yii Framework
Yii is another best PHP framework, and it’s a worthy competitor of other frameworks.
Yii popular due to how easy it is to set up. It gives high performance and right up there with Phalcon when it comes to the performance.
This makes it more economical to compare others.
Yii offers a robust set of components for developing the application.
It helps you can use to accelerate web application development.
However, it stands out due to its robust set of security features, which you can use to create highly secure projects.
Features:
Excellent speed and performance.
Use the default setup or customize it to meet your precise needs.
Create secure websites and applications.
9. Fat-Free Framework
Fat-Free has been developed in 2009 by Bong Cosca.
It is a powerful and simple framework to use. As the name indicates it is a micro-framework with less memory intake.
It takes less than 50KB space file which makes it one of the lightweight structured PHP frameworks.
Out of the best PHP frameworks, this was created almost completely in PHP with features like URL router, support of the multi-lingual application and cache engine.
There are many plug-ins available for extensive database back-end operations such as MSSQL, MySQL, PostgreSQL, SQLite, Sybase, MongoDB, DB2, CouchDB, and Flat File.
Features:
One of the widely used frameworks as it is reputed for the impressive speed
Highly modular framework
Clean, comprehensive and detailed documentation
There is no canned coding or a directory structure
Comes with multiple view engines
Can be used for creating robust web applications
Easy to learn and implement
10. Kohana
It is known not to have dependencies on other libraries and extensions.
It is also a lightweight PHP framework.
Optimized solutions employed to make it non-depend on another library during development.
It also a Model View Controller(MVC) architectural pattern.
It is well driven and supported by the community.
Features
Highly secure
Extremely lightweight
Short learning curve
Uses the MVC pattern
100% UTF-8 compatible
Loosely coupled architecture
Extremely easy to extend
11. FuelPHP
It is developed in 2014 and a relatively new PHP framework.
It is a powerful framework and created something new and exciting
comparing another framework.
It has many unique aspects of features that are also described in other sections.
Features:
Full support for HMVC
Hardened security out of the box
A unique command-line utility
12. Flight
The flight is a widespread micro structure meant for PHP developers and is known as a speedy, easy and flexible framework. The best part of Flight is that it allows developers to build heavy web applications promptly and easily. It requires PHP 5.3+.
Features
Uses static methods
Flight uses static methods, it does not require the application class to be instantiated.
Filters
A unique feature of Flight is something that the author calls filters. Filters are functions that can be executed before and after any other function and can change the parameters and the output of the said function.
13. AjaxAC
If you are working with Ajax application you need to have many smooth features.
It is offered by AjaxAC. It will be the best solution to developing Ajax applications.
Another, open-source framework from PHP, it helps in developing faster, easier and high-quality applications of all sizes.
When using AjaxAC you do not have to reload the entire page as it implements the XMLHttpRequest object to change the state of web pages using the HTTP sub-requests in the background.
Features:
A single class is used as self-contained for all application code
Calling PHP file/HTML page is spotless. All that is required is creating the application classes, then referencing the application Javascript and attaching any required elements to the application.
Built-in functionality for easy handling of Javascript events.
It makes the process of hooking with existing PHP Classes or MySQL database easier than other
14. Zikula
Zikula is open-sourced PHP frameworks based on the Symfony and Doctrine.
It is suitable for all range of project sizes from small and personal to enterprise-based projects.
It is incorporated many structures like Bootstrap 3 structure and Font Awesome. It delivers high-end performance when coming to the development of the application.
It includes new some exclusive features like elegant theme system, ModuleStudio, WYSIWYG editors, document originator, chat, galleries and many more.
Features
In well-maintained and high-quality components are used for providing high-end performance.
High-quality ecosystem feasible result are delivered fro application.
Zikula uses some of the Model-driven development tools.
It is known for creating dynamic content block creation and arrangement
15. Aura
When you are developing a basic app, Aura must be your priority for it. Because it's always a go-to option for developers for basic apps.
It consists of self-contained decoupled libraries with no dependencies.
This makes Aura to integrate the libraries and components separately into a project.
All the libraries are regularly maintained by the Aura community.
Features:
Configuration system makes the development process easier and speed up it.
Dependency injection container allows developers to add components separately.
Web request and response objects are easy to handle.
Standard I/O objects are used throughout the framework.
16. PHPixie
PHP developers looking for a simplified PHP framework opt for PHPixie because it is operational on the platform of MVC pattern, helping developers design applications in a short period.
With PHPixie you can get a strong foundation for development.
Most PHPixie is straightforward to study and perform flawlessly to create superior web applications.
Requiring lesser configuration and being easy to use, this is going to be one among more and more popular PHP frameworks in the coming days.
17. Medoo
Medoo is the lightest & an easily manageable PHP framework used to hasten the web development process.
You can learn Medoo easily and use it for development. More for handling databases it offers various options that is it is compatible with SQL databases such as MySQL, SQLite, MSSQL, Maria DB, Oracle, Postgre SQL, Sybase and more.
If you want to manage complicated coding and also entangled with the high number of codes than Medoo will be the option.
Features
Lightweight
It is portable with only one file and less than 100kb.
Powerful
It supports many features including various common and complex SQL queries, data mapping, and prevent SQL injection.
Friendly
You can use this with every PHP frameworks like Laravel, Codeigniter, Yii, Slim, and framework which supports singleton extension or composer.
Compatible
As already states it is compatible with may database technologies like MySQL, MSSQL, SQLite, MariaDB, PostgreSQL, Sybase, Oracle and more.
18. POP PHP
A strong design is used in the development of the POP PHP framework.
Even though it is simple to use with an efficient API.
It calls for PHP 5.3+ and manages to maintain its minimalism and lightweight nature.
It is used purely as a toolbox having perhaps having numerous novel features have been added to it.
It is more like the foundation of your applications.
Features
1. Application Object
2. Service Locator
3. Module Manager
4. Base Controller Class
19. Qcodo
Qcodo Development Framework is one of the awesome PHP Frameworks. It is a wholly object-oriented framework and open-source too.
It does not use unnecessary strain of coding for development so it was liked by many developers.
The websites that are powered by Qcodo are capable of generating over 100 million page views each month.
Organizations such as NASA and companies like HP where there is always this rigorous production of data are implementing Qcodo as it hassle-free to use.
Regardless of the application, you can implement Qcodo for almost anything and everything that includes both large scale enterprise applications and even the Web 2.0 startups.
Features
1. Global support
2. It supports object-oriented database querying library
3. Also, it comes with database profiling tools that are in-built
4. It comes with a fully-integrated PHP driven AJAX Support.
20. Seagull
If you want to build complicated applications then Seagull can be preferred. As it is one of the object-oriented PHP Frameworks.
If you are new to PHP and want to master in development then, this is where you should be starting.
It is easy to hunt down the Seagull library for sample applications. In which you can be tailor to fit into your requirements with ease.
Don’t worry if you are an expert, still, you can implement Seagull because it provides you with a variety of options that includes a modular codebase, standards, best practices that will guide you through building some of the best applications.
A number of the command line, GUI apps and web applications have been powered by the Seagull framework from PHP.
Help and assistance are available at any time because of the active community that Seagull possesses.
Features
Ease of use: It is great for prototyping complex projects
Integrated with ORM for RAD development
It is highly configurable with other frameworks, easy to integrate with 3rd party code
It has loosely coupled components and you can use the template engine of your choice.
21. BlueShoes
If you want to have the Content Management System inside the framework then go for Blue Shoes.
It does not compromise on security and quality for application but also it is easier and faster way of developing the application.
Blue Shoes provides other exciting features that provide unconditional support for the database.
With the help of widely-used MySQL database, it makes database access easier also it support for MSSQL and Oracle.
22. Nette
Nette is a powerful helping developer who creates better websites.
Radical technology is used in Nette which helps in t eliminating security holes and their mishandling like in XSS, session hijacking, and session fixation.
It has a strong debugging tool which helps to discover bugs easily
Features:
Nette is open source and is distributed under the MIT license.
Built around good programming practices
Nette is built to help developers create good, maintainable code using the DRY principle
It helps to develop applications faster.
23. Cappuccino
When you have a short period for development the application then go with Cappuccino.
It is Build on JS but works well with the PHP backend to any application.
It is popular for developing an application in less time without missing out on essentials.
It is Created by the 280North team of Motorola.
It got popular for its rich features and ability to develop applications that might not have been possible on other framework bases.
24.Limonade
Limonade has high-quality web designing and development solutions.
It also provides a significant solution for complex problems
Apart from this, Limonade is one of the excellent PHP frameworks in assisting developers for speedy prototyping solutions.
25. Stratus
Like Qcodo, Stratus is both an object-oriented and open-source PHP Framework!
It is mainly used for rapid development of PHP web applications. Also, you do not worry about safety and security when working on Stratus.
Conclusion
The great thing if you use PHP frameworks, you can make your development process much faster, easier and more fun.
All PHP frameworks are different and unique from each other and offer and amazing features.
Our suggestion is to use only what you consider the most appropriate and easy to learn a framework for your project. Most importantly, which suits your application development and satisfies your business needs.
If you are going to develop your application in PHP you can hire our highly skilled PHP Developers as you want.
Click here to read more: https://www.infinijith.com/blog/framework/best-php-frameworks
0 notes
Text
How important is coding?
Coding is and has always been the most futuristic job. It will remain relevant until the end of technology because apparently without coding you cannot design a program or give a new shape to A.I (Artificial Intelligence).
Coding, also known as programming, basically implies writing codes for computer programming or building web pages and applications. HTML/CSS, PHP, Javascript, C+, and Dot Net are few of the examples of most adopted programming languages. Whatever we see inside a computer, on the internet, or machines with a graphical interface such as a smartphone is basically made from coding.
Coding as a Tech Job
8 out of 25 jobs posted are Tech Jobs. With the rising demand of developers, coding has become an essential skill in almost every resume.
The essence and importance of programming cannot be denied in today’s world where almost everything built by human runs on arrays of codes.
Large conglomerates such as Apple, Google, and Microsoft who house thousands of employees demand expert programmers. Although an exceptional case, a programmer made as much as $3million a year in salary and stock at Google. This makes coding the most sought after job in the world.
The most sought after Tech jobs in the world are as follows;
· Information Technology (IT) worker
· Data Analysts
· Artists and designers
· Engineers
· Scientists
According to the U.S. Bureau of Labor Statistics, in 2012, the average salary for an application software developer was $93,000, with only 10 percent of such developers making more than $139,000 in salary.
10x Engineer
10x Engineer implies that the computer engineer can code 10 times faster any average coder or he can do 10 times more than any coder. They are the highest-paid tech workers in the world. Although a popular concept, there are likely only 1% 10x Engineers in the world.
Along with the coding, testing the application, debugging, and designing (UI/X) are equally important job descriptions. However, the demand for a coder exceeds any other tech jobs.
Importance of Coding
Developing a program through coding involves a series of steps where a programmer will define a problem, plans a solution, code, test the code, and finally document the program. The importance of coding can be simplified through the following points.
Systems Knowledge
Coding helps a programmer to gain a full understanding of the how and why of computer systems, including system limitations. They can work around those limitations to fully maximize the use of the equipment and its accessories.
Creativity Platform
Coding has always been a platform to showcase creativity, especially for entertainment. With the help of coding, the game develops can create new video games, graphics, and animations to showcase new business ideas or to resolve a particular problem.
Interactive Education
Coding helps in interactive education by offering interactive web applications. Used on online learning platforms, these applications have allowed distance-learning programs to take off. Today, almost all major learning institutions have some form of online learning implementation, thanks to computer programming such as cloud computing.
Defining the Future
Every major futuristic accomplishment has been done by programming. Future-technology such as voice-recognition, artificial intelligence, and touch-simulation in devices keep evolving and getting better with the advent of new coding. The rise in online shopping gave way to eCommerce and easy online payment systems. A.I. in smartphone and websites can offer suggestions, advice, or solutions at ago.
Machine Language
Since computers work with numbers, programming allows a person to represent machine-language in a human-readable format. This reduces the chances of introducing errors and wasted time in debugging and correcting mistakes
Different Programming Languages
A programming language is known as a vocabulary with a set of grammatical rules instructing a computer or computing device to perform specific tasks.
Although the term programming language usually referred to high-level languages, such as BASIC, C, C++, COBOL, Java, FORTRAN, Ada, and Pascal, today it is used for almost every set of a programming languages such as PHP, Javascript, Python, Dot Net, and C+.
Some of the most implemented programming languages are as follows;
PHP

More than 80% of the internet is powered by PHP. Everything ranging from website, applications, to portals are designed in PHP. Since its inception, PHP developers have always been in high demand. Due to the availability of open-source content management systems, frameworks and a good compromise of speed, code quality, and development PHP are chosen as the developer’s tool for years.
Laravel remains one of the most adopted PHP frameworks that is used to develop dynamic web pages.
C++
C++ is an all-purpose object-oriented programming (OOP) language. C and C+ were its predecessors. The main highlight of C++ is a collection of predefined classes, which are data types that can be instantiated multiple times
Dot Net

The advent of Dot Net improved development experience and relieved engineers from security operations, active memory management, and other low-level efforts that C/C++ developers had to bother with.
.NET is a language-independent framework that provides programming guidelines to develop a wide range of applications for web, mobile, and Windows-based applications. The .NET framework can work with several programming languages such as C#, VB.NET, C++, and F#.
Javascript
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat.
AngularJS

AngularJS was developed to tackle the growing needs of developers. It is a structural framework for dynamic web apps and uses HTML as the template language. It is a JavaScript-based open-source framework used for building a front-end web application.
NodeJS
Node JS relies on Javascript and uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. It remains perfect for data-intensive real-time applications running across distributed devices.
ReactJS
React JS is an open-source JavaScript library designed by Facebook. It is used for building user interfaces or front-end framework specifically for single-page applications. It is used for handling the view layer for web and mobile apps.
Most Demanded Programming Language
Here are the Top 7 programming languages with the most job postings on Indeed as of January 2019.
· Java – 65,986 jobs
· Python – 61,818 jobs
· Javascript – 38,018 jobs
· C++ – 36,798 jobs
· C# – 27,521 jobs
· PHP – 16,890 jobs
· PERL – 13, 727 jobs
How can I learn to code?

It is easy to learn coding if you can invest few hours of your day learning the basics of programming, such as language (PHP for dynamic web page, Swift or C for iOS mobile apps, and Java for Android apps), code implementation, toolset, framework, testing, and developing applications or web pages.
Online Courses
Online courses offer you a flexible schedule. You can learn the coding at the comfort of your home. Most online courses offer classes and conduct exams in return for a small fee.
The Odin Project is one of the sites offering an online course on programming for solo practitioners.
Subscription-model certification courses from Udacity or Treehouse offer an opportunity to ask a tutor.

You can get free practical JavaScript course from Watch and Code, which revolves around a single project that you continually iterate.
Watching videos and tutorials, reading e-books, and practicing your own project can help you gain programming knowledge quicker than you can think.
The ability to code comes with greater benefits. You can find a high-paying job at almost any Tech company. With the rising demand for programmers, you are less likely to be returned from job interviews.
The important thing to keep in mind to keep yourself updated. With the changing face of technology comes bigger challenges such as keeping yourself updated, learning the additional language for larger outreach, and collaborating with like-minded personnel’s. The GitHub offers a large resource of knowledge, codes, and an opportunity to collaborate with programmers around the world.
Searchable Design llc
Searchable Design in an it company located in Des Monies, Urbandale. Searchable Design is an enthusiastic group of IT professionals in Des Moines working to provide endless web,mobile solutions in des moines for businesses and individuals alike. From a niche website to varieties of online business tool, we design, manage and upgrade everything according to your need and requirement.
#importanceofcoding#differenttypesofprogramminglanguage#searchabledesign#itsolutionindesmoines#itcompanyindesmoines#itcompanyinurbandale#onlinecourseforprogramminglanguage#mostdemandedprogramminglanguage#webdevelopmentindesmoines
0 notes
Text
October 07, 2018 at 10:01PM - The Complete Learn to Code Masterclass Bundle (97% discount) Ashraf
The Complete Learn to Code Masterclass Bundle (97% discount) Hurry Offer Only Last For HoursSometime. Don't ever forget to share this post on Your Social media to be the first to tell your firends. This is not a fake stuff its real.
C++ is one of the most important programming languages in software development but many people never learn it because it can be exceedingly difficult. In this step-by-step course, you’ll learn the basics of C++ gradually through hands-on guidance. You won’t be thrust into any complicated programming too fast and you’re free to learn at your own pace. By course’s end, you’ll have a solid foundation from which to build on.
Access 42 lectures & 3 hours of content 24/7
Discover how to write C++ programs from scratch
Understand C++ concepts like functions & variables and object oriented programming
Learn what pointers are & how to use them
Discover how to handle exceptions in C++ programs
Familiar with both front- and back-end development, full-stack developers know the programming process from top to bottom, making them tremendously valuable (and highly paid) pros in their field. Jump into this full-stack primer, and you’ll learn how to build your own programming projects from start to finish. You’ll get up to speed with core tools, like HTML and JavaScript, as well as Laravel, the fastest-growing PHP framework today. With a hands-on e-commerce project to work through, you’ll develop real programming skills as you learn how to fetch data, build shopping carts, and more from scratch.
Access 167 lectures & 19.5 hours of content 24/7
Familiarize yourself w/ core full-stack dev tools, like HTML, CSS, PHP & Bootstrap
Get hands-on training w/ Laravel, the fastest-growing PHP framework
Refine your skills w/ mini projects included in almost every section
Learn how to work with shopping carts, online payments & more w/ a hands-on e-commerce project
If you’ve always wanted to build and design your own website, this course is the ideal place to start. The instructor makes it look easy, taking you through the latest Web technologies: HTML5, CSS3, and even some jQuery. By building projects alongside the video instruction, you’ll get a true hands-on feel for the basic building blocks of the web you surf daily.
Learn & apply HTML5 and CSS skills immediately w/ 11-hours of video content
Build a completely unique, beautifully-designed & responsive landing page
Focus on modern design for any screen size w/ responsive websites
Create a fully optimized website from scratch in 7 steps
Learn where to find free design resources like images, icons & fonts
Get introduced to using jQuery to build stand-out effects
Optimize your site for search engines & speed
JavaScript is one of the cornerstones of the web and absolutely essential to learn if you want to do any kind of web development. In this course, you’ll develop the core skills you need to apply JavaScript to your web projects. Ideal for beginners, JavaScript is relatively easy to get started with yet it’s an excellent gateway to learning other scripting languages.
Access 45 lectures & 4 hours of content 24/7
Create your first JavaScript code
Learn how to add JavaScript to your web pages
Understand the structure of JavaScript
Discover key JavaScript components like Functions, Arrays, Objects, Loops & conditionals
Explore JavaScript Core functionality like Math, Strings, literals identifiers & more
C# is a multi-paradigm programming language providing support for software engineering principles such as strong type checking, array bound checking, automatic garbage collection, and more. The newest release, C# 7 has a host of new features to build powerful cross-platform apps. In this course, you’ll learn everything you need to know to start developing applications using C# 7’s newest features, as well as the newest version of the .NET Core.
Access 44 lectures & 5 hours of content 24/7
Get an introduction to C# & .NET
Learn the new features of C# 7 & the new version of the ASP.Net Core Entity Framework
Dicuss more advanced concepts of C# like delegates, lambda expressions, & LINQ
Google Go, or Golang, has taken the world by storm due to its system-level access and a design that allows programmers to create multi-core programs. It’s the first development language designed specifically for the multi-core CPU computers that have been on the market for the last decade or so. As you may suspect, it was created by developers at Google to solve deficiencies they were facing with conventional computer languages and is an extremely valuable language to know in the 21st century.
Access 51 lectures & 5 hours of content 24/7
Get an introduction to Google Go
Discuss variables & constants in Google Go
Advance to arrays, slices, range loops & other advanced topics
Python’s one of the easiest yet most powerful programming languages you can learn, and it’s proven its utility at top companies like Dropbox and Pinterest. In this quick and dirty course, you’ll learn to write clean, efficient Python code, learning to expedite your workflow by automating manual work, implementing machine learning techniques, and much more.
Dive into Python w/ 9.5 hours of content
Acquire the database knowledge you need to effectively manipulate data
Eliminate manual work by creating auto-generating spreadsheets w/ xlsxwriter
Master machine learning techniques like sk-learn
Utilize tools for text processing, including nltk
Learn how to scrape websites like the NYTimes & Washington Post using Beautiful Soup
Complete drills to consolidate your newly acquired knowledge
Java is one of the most commonly used programming languages on earth, having contributed to just about every web app or website. If you’ve ever been interested in programming, then the simplicity and flexibility of Java is the perfect place to start. By the end of this course, you’ll be writing full programs like a pro.
Access 50 lectures & 8 hours of content 24/7
Use video lectures, lab exercises, & code examples to enhance your learning
Gain a full understanding of Java SE programming
Explore the basics of Java syntax & the complexities of Object Oriented Programming
Write Java programs that run on PC, Mac, or Linux machines
Git is the most widely-used and supported distributed version control system used by software engineering professionals. It’s a protocol that streamlines programming by batch tracking the history of file edits, allowing developers to pinpoint the source and time of any change. Learn to handle any size project quickly and efficiently with this complete Git course.
Get an introduction to the Git source control system w/ 7 hours & 83 lectures
Jump right in w/ installation for Windows & Mac
Manage, move, rename & delete files
Create & fork repositories w/ GitHub
Learn & practice the basic commands to start a new project w/ Git
Experience the draw of Git as a SCM w/ in-depth exploration of Branching & Merging
Learn to rebase & stash work
Make comparisons in Git
from Active Sales – SharewareOnSale https://ift.tt/2y9MGks https://ift.tt/eA8V8J via Blogger https://ift.tt/2yjxVeg #blogger #bloggingtips #bloggerlife #bloggersgetsocial #ontheblog #writersofinstagram #writingprompt #instapoetry #writerscommunity #writersofig #writersblock #writerlife #writtenword #instawriters #spilledink #wordgasm #creativewriting #poetsofinstagram #blackoutpoetry #poetsofig
0 notes
Text
All about PHP Frameworks! Which is better to use & learn for Custom Web Applications & Why?

PHP is essentially the most loved programming language when it comes to Website Development as well as complex Web Applications. However, Web Development can become trickier with increasing complexity. In such cases, PHP frameworks such as Codigniter, Laravel, Symphony and others come to the rescue. Here is everything you need to know about them and learn how to make most of Codeigniter Development, Laravel Development, Symphony Development, Zend Development etc…
CodeIgniter: Codeigniter is among the oldest PHP frameworks, having been around since 2006. Some of the features worth mentioning here are:
Model-View-Controller Based System: ensures scalable and well segregated development.
Light Weight: Web applications built on CodeIgniter are blazingly fast.
Database support
Support for email, image manipulation, FTP upload and much more.
Codeigniter Development is fun when you work with some of the brightest minds in the industry. Check with your service provider how well versed is their employees in CodeIgniter.
Laravel Development
Though Laravel is a late entrant to the field, it is essentially the hottest property in the town. As per a survey by popular site Sitepoint, it is the most preferred choice among developers. What is the reason behind the popularity of Laravel development? Here are some of the reasons behind its stupendous popularity:
Support for multiple file systems
Authentication feature that saves developers from writing tons of authentication related code
Route caching to speed up the application route registration
Highly improved method injection feature
Events object that helps speeding up Laravel development
Inbuilt templates that help in creating awesome content with lightning quick speed
Eloquent ORM to write database queries
MVC architecture support
Symphony Development
Symphony is yet another popular PHP framework that is immensely rich in incredible features. This is precisely the reason why it has enjoyed continuous love from developers all over the globe. Here are some of such features that deserve a mention:
Rich in features that make it flexible: Bundles are collection of files that make installation of new features tremendously easy. For instance, adding a new blog or a shopping cart can be done pretty easily by doing simple configuration. A number of similar such features essentially make Symphony a darling to web developers.
Commercial support: Commercial support from its parent company, SensioLabs has ensured that it has professionally curated tutorials and a lot of support as well.
-Ease of testing: PHPUnit Testing Library makes unit testing considerably easy.
Large community: Over the years, Symphony developers have ushered in a large community and by seeking support from the same one can tide over even the most complex problems.
Zend Development
Reasons to go for Zend development:
Extensible: Based on object oriented programming, Zend framework is immensely extendable. Zend developers can write awesome applications using its features like interfaces and inheritance without having to disturb the Zend framework codebase.
Decoupling lets you to use the features you need and skip everything else: Zend MVC architecture is so flexible that it lets you use only the features that are required for your application and skip those that you don’t need. This is essentially made possible with the help of classes based approach.
A variety of components that let you perform awesome tasks: You can do a lot with the vast variety of components like authentication, access control, create forms, RSS feed and so on with easily reusable components. So, step forward and implement that cracking functionality that you always wanted to add.
CakePHP: Here are some features of CakePHP, another immensely popular PHP framework that enjoys favor from many PHP developers:
MVC architecture: You can build scalable and inherently complex web applications using this framework
Object Relation Mapping: With the help of this feature you can write database queries with immense ease
Class inheritance: Class inheritence helps you to scale applications without unnecessary code and complications
Built-in validation: The validation related tasks can be completed without having to write enormous pieces of code thanks to the built-in validation featue
Yii: Some noteworthy features of Yii PHP framework:
Tremendous speed: Yii PHP framework is immensely fast and web applications written on it run like a charm
Form validation made easy
Enhanced security
CRUD validation
Authentication and Authorization features are in-built
The most popular PHP framework
Among all the PHP frameworks available today, the most popular one among these seems to be Laravel, given that it is used by over 50% of all PHP developers. Codeigniter and Symphony are up next due to their stupendous features, but even then they are far behind Laravel in terms of overall popularity.
Author Bio: Pushpendra Singh is a Freelance Codeigniter Developer working with F5 Buddy, who loves to develop Website, mobile and web applications. F5 Buddy is one of the amongst leading Development Outsourcing Company, which provides totally different array of real software package solutions like Custom software Development, IT Outsourcing Services, Web Application Development services to its clients globally.
0 notes
Text
collect.js- Convenient and dependency free wrapper for working with arrays and objects https://t.co/VhM7zeH5gr #Laravel-Collections
collect.js- Convenient and dependency free wrapper for working with arrays and objects https://t.co/VhM7zeH5gr #Laravel-Collections
— Macronimous.com (@macronimous) June 26, 2018
from Twitter https://twitter.com/macronimous June 26, 2018 at 11:50PM via IFTTT
0 notes
Photo
Office 365 being rewritten in JavaScript
#390 — June 15, 2018
Read on the Web
JavaScript Weekly
JavaScript Engine Fundamentals — A fantastic writeup (with video, if preferred) looking at the key parts of major JavaScript VMs/engines and how they interact with the code you write.
Mathias Bynens
Polly.js: Record, Replay, and Stub HTTP Interactions — A library from Netflix for recording, replaying and stubbing HTTP interactions via native browser APIs. GitHub repo.
Netflix
💻 New Course: A Practical Guide to Algorithms with JavaScript — Bored by the academic approach of most data structures and algorithms courses? This is for you. Solve algorithms and analyze space and time complexity in both an interview setting and in your day-to-day development.
Frontend Masters sponsor
Office 365 Is Being Rewritten in JavaScript — Joining Skype, Microsoft Teams, and VS Code. React Native Windows is the approach used, making it possible to build seamless Windows 10 and Xbox One apps with React.
Sean Thomas Larkin on Twitter
Vue Native: Build Native Mobile Apps with Vue.js — React has React Native, and now if you’re a Vue.js developer, you could give this a try. Unlike React Native this isn’t an official project from the same team and is essentially a Vue wrapper around React Native itself. Introductory article.
GeekyAnts
How V8's Concurrent Marking Frees Up The Main Thread — ‘Marking’ is a key step in V8 6.4’s garbage collection process and now this process takes place on separate worker threads meaning more time for your code on Chrome 64+ and Node 10+.
Mathias Bynens
Introducing 'The GraphQL Guide' — John Resig, the creator of jQuery, has co-written a book aiming to show you why GraphQL APIs are “the true successor to REST APIs”.
John Resig and Loren Sands-Ramshaw
Vue.js Passes React in Terms of GitHub Star Count — A vanity metric for sure, but an interesting one nonetheless. React still has significantly more downloads each day but Vue’s community is particularly vibrant and eager.
Dan Abramov on Twitter
The Biggest Lead Developer Conference Yet Is Coming to London in 2 Weeks
The Lead Developer London sponsor
💻 Jobs
React/Full-Stack Engineer (Remote) — Join our small, distributed team as we build the world’s largest open library of freely usable visuals. Open to all, regardless of experience and background.
Unsplash
Have You Tried Vettery? — Vettery matches top tech talent with fast-growing companies. Take a few minutes to join our platform.
Vettery
📘 Tutorials
Understanding the Almighty Reducer — A beginner-friendly walkthrough of using JavaScript’s reduce method.
Sarah Drasner
What's New in ES2018 — Including async iteration, Promise.finally(), and rest/spread properties.
Craig Buckler
▶ Look, No Hands! — Brain Controlled JavaScript — Fun with thought processed interactions using a brain sensor with JavaScript.
Charlie Gerard
▶ Learn to Build a Slack Integration — A demo of Slack’s new developer features, with an introduction to Actions, showing what it enables for developers, and some possible use cases.
Slack sponsor
Submitting HTML Forms using Vue, React, or Hyperapp
Ogundipe Samuel
An Introduction to Sails.js — A Rails-esque MVC framework for Node webapps.
Ahmed Bouchefra
▶ How to Set Up A Windows Dev Environment That Feels Like $HOME — This isn’t JS specific but we’re always hearing of developers trying out Windows lately so this could be helpful.
Sarah Cooley and Tara Raj
▶ How to Code Your Own Discord Bot with Discord.js
Dapper Dino
🔧 Code and Tools
Parcel 1.9 Released with Tree Shaking and 2x Faster Watcher — If you want a fast, easy, zero-config bundler.
Devon Govett
A Much Faster Way to Debug Code Than with Breakpoints or Console.log — Wallaby catches errors in your tests and displays the results of expressions right in your editor as you type.
Wallaby.js sponsor
Licensed: A CLI for Adding a LICENSE File to Your Projects
Mihir Chaturvedi
collect.js: 91 Convenience Methods for Arrays and Objects — A similar API to Laravel Collections: chunk, flatten, shuffle, firstWhere, etc.
Daniel Eckermann
Pickr: A Flat, Simple, Dependency-Free Color Picker — Live demo. It’s nice.
Simon Wep
Math.js: An Extensive Math Library for JavaScript and Node — There’s a CoffeeScript-oriented intro too, if that’s your bag.
Jos de Jong
jeelizWeboji: Realtime JS Face Tracking and Facial Expression Detection
Bourry Xavier
HyperMD: A WYSIWYG Markdown Editor for Browsers — Written in TypeScript. Demo here.
Lv Yang
Vuesax: A Frontend Vue.js Components Framework
Lusaxweb
by via JavaScript Weekly https://ift.tt/2Mu0xI3
0 notes
Text
Building a Vue SPA with Laravel Part 3
News / February 16, 2018
Building a Vue SPA with Laravel Part 3
We will continue building our Vue SPA with Laravel by showing you how to load asynchronous data before the vue-router enters a route.
We left off in Building a Vue SPA With Laravel Part 2 finishing a UsersIndex Vue component which loads users from an API asynchronously. We skimped on building a real API backed by the database and opted for fake data in the API response from Laravel’s factory() method.
If you haven’t read Part 1 and Part 2 of building a Vue SPA with Laravel, I suggest you start with those posts first and then come back. I’ll be waiting for you!
In this tutorial we are also going to swap out our fake /users endpoint with a real one powered by a database. I prefer to use MySQL, but you can use whatever database driver you want!
Our UsersIndex.vue router component is loading the data from the API during the created() lifecycle hook. Here’s what our fetchData() method looks like at the conclusion of Part 2:
created() { this.fetchData(); }, methods: { fetchData() { this.error = this.users = null; this.loading = true; axios .get('/api/users') .then(response => { this.loading = false; this.users = response.data; }).catch(error => { this.loading = false; this.error = error.response.data.message || error.message; }); } }
I promised that I’d show you how to retrieve data from the API before navigating to a component, but before we do that we need to swap our API out for some real data.
Creating a Real Users Endpoint
We are going to create a UsersController from which we return JSON data using Laravel’s new API resources introduced in Laravel 5.5.
Before we create the controller and API resource, let’s first set up a database and seeder to provide some test data for our SPA.
The User Database Seeder
We can create a new users seeder with the make:seeder command:
php artisan make:seeder UsersTableSeeder
The UsersTableSeeder is pretty simple right now—we just create 50 users with a model factory:
<?php use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { public function run() { factory(App\User::class, 50)->create(); } }
Next, let’s add the UsersTableSeeder to our database/seeds/DatabaseSeeder.php file:
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call([ UsersTableSeeder::class, ]); } }
We can’t apply this seeder without first creating and configuring a database.
Configuring a Database
It’s time to hook our Vue SPA Laravel application up to a real database. You can use SQLite with a GUI like TablePlus or MySQL. If you’re new to Laravel, you can go through the extensive documentation on getting started with a database.
If you have a local MySQL instance running on your machine, you can create a new database rather quickly from the command line with the following (assuming you don’t have a password for local development):
mysql -u root -e"create database vue_spa;" # or you could prompt for the password with the -p flag mysql -u root -e"create database vue_spa;" -p
Once you have the database, in the .env file configure the DB_DATABASE=vue_spa. If you get stuck, follow the documentation which should make it easy to get your database working.
Once you have the database connection configured, you can migrate your database tables and add seed data. Laravel ships with a Users table migration that we are using to seed data:
# Ensure the database seeders get auto-loaded composer dump-autoload php artisan migrate:fresh --seed
You can also use the separate artisan db:seed command if you wish! That’s it; you should have a database with 50 users that we can query and return via the API.
The Users Controller
If you recall from Part 2, the fake /users endpoint found in the routes/api.php file looks like this:
Route::get('/users', function () { return factory('App\User', 10)->make(); });
Let’s create a controller class, which also gives us the added benefit of being able to use php artisan route:cache in production, which is not possible with closures. We’ll create both the controller and a User API resource class from the command line:
php artisan make:controller Api/UsersController php artisan make:resource UserResource
The first command is adding the User controller in an Api folder at app/Http/Controllers/Api, and the second command adds UserResource to the app/Http/Resources folder.
Here’s the new routes/api.php code for our controller and Api namespace:
Route::namespace('Api')->group(function () { Route::get('/users', 'UsersController@index'); });
The controller is pretty straightforward; we are returning an Eloquent API resource with pagination:
<?php namespace App\Http\Controllers\Api; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Resources\UserResource; class UsersController extends Controller { public function index() { return UserResource::collection(User::paginate(10)); } }
Here’s an example of what the JSON response will look like once we wire up the UserResource with API format:
{ "data":[ { "name":"Francis Marquardt", "email":"[email protected]" }, { "name":"Dr. Florine Beatty", "email":"[email protected]" }, ... ], "links":{ "first":"http:\/\/vue-router.test\/api\/users?page=1", "last":"http:\/\/vue-router.test\/api\/users?page=5", "prev":null, "next":"http:\/\/vue-router.test\/api\/users?page=2" }, "meta":{ "current_page":1, "from":1, "last_page":5, "path":"http:\/\/vue-router.test\/api\/users", "per_page":10, "to":10, "total":50 } }
It’s fantastic that Laravel provides us with the pagination data and adds the users to a data key automatically!
Here’s the UserResource class:
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\Resource; class UserResource extends Resource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'name' => $this->name, 'email' => $this->email, ]; } }
The UserResource transforms each User model in the collection to an array and provides the UserResource::collection() method to transform a collection of users into a JSON format.
At this point, you should have a working /api/users endpoint that we can use with our SPA, but if you are following along, you will notice that our new response format breaks the component.
Fixing the UsersIndex Component
We can quickly get our UsersIndex.vue Component working again by adjusting the then() call to reference the data key where our user data now lives. It might look at little funky at first, but response.data is the response object, so the user data can be set like the following:
this.users = response.data.data;
Here’s the adjusted fetchData() method that works with our new API:
fetchData() { this.error = this.users = null; this.loading = true; axios .get('/api/users') .then(response => { this.loading = false; this.users = response.data.data; }).catch(error => { this.loading = false; this.error = error.response.data.message || error.message; }); }
Fetching Data Before Navigation
Our component is working with our new API, and it’s an excellent time to demonstrate how you might fetch users before navigation to the component occurs.
With this approach, we fetch the data and then navigate to the new route. We can accomplish this by using the beforeRouteEnter guard on the incoming component. An example from the vue-router documentation looks like this:
beforeRouteEnter (to, from, next) { getPost(to.params.id, (err, post) => { next(vm => vm.setData(err, post)) }) },
Check the documentation for the complete example, but suffice it to say that we will asynchronously get the user data, once complete, and only after completion, we trigger next() and set the data on our component (the vm variable).
Here’s what a getUsers function might look like to asynchronously get users from the API and then trigger a callback into the component:
const getUsers = (page, callback) => { const params = { page }; axios .get('/api/users', { params }) .then(response => { callback(null, response.data); }).catch(error => { callback(error, error.response.data); }); };
Note that the method doesn’t return a Promise, but instead triggers a callback on completion or failure. The callback passes to arguments, an error, and the response from the API call.
Our getUsers() method accepts a page variable which ends up in the request as a query string param. If it’s null (no page passed in the route), then the API will automatically assume page=1.
The last thing I’ll point out is the const params value. It will effectively look like this:
{ params: { page: 1 } }
And here’s how our beforeRouteEnter guard uses the getUsers function to get async data and then set it on the component while calling next():
beforeRouteEnter (to, from, next) { const params = { page: to.query.page }; getUsers(to.query.page, (err, data) => { next(vm => vm.setData(err, data)); }); },
This piece is the callback argument in the getUses() call after the data is returned from the API:
(err, data) => { next(vm => vm.setData(err, data)); }
Which is then called like this in getUsers() on a successful response from the API:
callback(null, response.data);
The beforeRouteUpdate
When the component is in a rendered state already, and the route changes, the beforeRouteUpdate gets called, and Vue reuses the component in the new route. For example, when our users navigate from /users?page=2 to /users?page=3.
The beforeRouteUpdate call is similar to beforeRouteEnter. However, the former has access to this on the component, so the style is slightly different:
// when route changes and this component is already rendered, // the logic will be slightly different. beforeRouteUpdate (to, from, next) { this.users = this.links = this.meta = null getUsers(to.query.page, (err, data) => { this.setData(err, data); next(); }); },
Since the component is in a rendered state, we need to reset a few data properties before getting the next set of users from the API. We have access to the component. Therefore, we can call this.setData() (which I have yet to show you) first, and then call next() without a callback.
Finally, here’s the setData method on the UsersIndex component:
setData(err, { data: users, links, meta }) { if (err) { this.error = err.toString(); } else { this.users = users; this.links = links; this.meta = meta; } },
The setData() method uses object destructuring to get the data, links and meta keys coming from the API response. We use the data: users to assign data to the new variable name users for clarity.
Tying the UsersIndex All Together
I’ve shown you pieces of the UsersIndex component, and we are ready to tie it all together, and sprinkle on some very basic pagination. This tutorial isn’t showing you how to build pagination, so you can find (or create) fancy pagination of your own!
Pagination is an excellent way to show you how to navigate around an SPA with vue-router programmatically.
Here’s the full component with our new hooks and methods to get async data using router hooks:
<template> <div class="users"> <div v-if="error" class="error"> <p></p> </div> <ul v-if="users"> <li v-for="{ id, name, email } in users"> <strong>Name:</strong> , <strong>Email:</strong> </li> </ul> <div class="pagination"> <button :disabled="! prevPage" @click.prevent="goToPrev">Previous</button> <button :disabled="! nextPage" @click.prevent="goToNext">Next</button> </div> </div> </template> <script> import axios from 'axios'; const getUsers = (page, callback) => { const params = { page }; axios .get('/api/users', { params }) .then(response => { callback(null, response.data); }).catch(error => { callback(error, error.response.data); }); }; export default { data() { return { users: null, meta: null, links: { first: null, last: null, next: null, prev: null, }, error: null, }; }, computed: { nextPage() { if (! this.meta || this.meta.current_page === this.meta.last_page) { return; } return this.meta.current_page + 1; }, prevPage() { if (! this.meta || this.meta.current_page === 1) { return; } return this.meta.current_page - 1; }, paginatonCount() { if (! this.meta) { return; } const { current_page, last_page } = this.meta; return `${current_page} of ${last_page}`; }, }, beforeRouteEnter (to, from, next) { getUsers(to.query.page, (err, data) => { next(vm => vm.setData(err, data)); }); }, // when route changes and this component is already rendered, // the logic will be slightly different. beforeRouteUpdate (to, from, next) { this.users = this.links = this.meta = null getUsers(to.query.page, (err, data) => { this.setData(err, data); next(); }); }, methods: { goToNext() { this.$router.push({ query: { page: this.nextPage, }, }); }, goToPrev() { this.$router.push({ name: 'users.index', query: { page: this.prevPage, } }); }, setData(err, { data: users, links, meta }) { if (err) { this.error = err.toString(); } else { this.users = users; this.links = links; this.meta = meta; } }, } } </script>
If it’s easier to digest, here’s the UsersIndex.vue as a GitHub Gist.
There are quite a few new things here, so I’ll point out some of the more important points. The goToNext() and goToPrev() methods demonstrate how you navigate with vue-router using this.$router.push:
this.$router.push({ query: { page: `${this.nextPage}`, }, });
We are pushing a new page to the query string which triggers beforeRouteUpdate. I also want to point out that I’m showing you a <button> element for the previous and next actions, primarily to demonstrate programmatically navigating with vue-router, and you would likely use <router-link /> to automatically navigate between paginated routes.
I have introduced three computed properties (nextPage, prevPage, and paginatonCount) to determine the next and previous page numbers, and a paginatonCount to show a visual count of the current page number and the total page count.
The next and previous buttons use the computed properties to determine if they should be disabled, and the “goTo” methods use these computed properties to push the page query string param to the next or previous page. The buttons are disabled when a next or previous page is null at the boundaries of the first and last pages.
There’s probably a bit of redundancy in the code, but this component illustrates using vue-router for fetching data before entering a route!
Don’t forget to make sure you build the latest version of your JavaScript by running Laravel Mix:
# NPM npm run dev # Watch to update automatically while developing npm run watch # Yarn yarn dev # Watch to update automatically while developing yarn watch
Finally, here’s what our SPA looks like after we update the complete UsersIndex.vue component:
What’s Next
We now have a working API with real data from a database, and a simple paginated component which uses Laravel’s API model resources on the backend for simple pagination links and wrapping the data in a data key.
Next, we will work on creating, editing, and deleting users. A /users resource would be locked down in a real application, but for now, we are just building CRUD functionality to learn how to work with vue-router to navigate and pull in data asynchronously.
We could also work on abstracting the axios client code out of the component, but for now, it’s simple, so we’ll leave it in the component until Part 4. Once we add additional API features, we’ll want to create a dedicated module for our HTTP client.
via Laravel News http://ift.tt/2BxHnhd
0 notes
Photo
New Post has been published on https://programmingbiters.com/recent-views-view-counter-log-in-laravel/
Recent Views & View Counter log in Laravel
Sometimes we need to implement a view counter to keep track of how many times a post was viewed. Of course we can simply create a count variable and keep incrementing it with every GET request. But what if we consider logging recent views to keep track of the recent posts an user has viewed? In that case, a simple counter variable isn’t very helpful.
A simple yet flexible solution is to create a pivot between users and posts that stores how many times a post has been viewed by an user. We will create a separate entry for each user viewing a post. The overall procedure would be something like the following:
When an user views a post, dispatch a Job, e.g UserViewedPost , that will handle all the logic for logging the view.
Create a collection of the posts this user has viewed. If the collection contains the post currently being viewed, simply increment the view count. If the collection does not contain the current post, attach the current post to the collection.
To calculate total views of a post, sum up the number of times any user has viewed that particular post.
TL;DR: A complete implementation can be found on this Github repo 🙂
# Setting up the migrations
Let’s create a pivot table user_post_views to store all the view related data.
public function up() Schema::create('user_post_views', function (Blueprint $table) $table->increments('id'); $table->integer('user_id')->unsigned(); $table->integer('post_id')->unsigned(); $table->integer('count'); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); );
user_id will store the id of the user who is viewing the post. post_id will contain the id of the post currently being viewed. count is the number of times this user has viewed this post.
# Setting up the relationship
Relationship between User and Post is simple – a user may view many postsand a post may be viewed by many users. Therefore, we setup a many to manyrelationship. Let’s define these relationships in the corresponding models.
Let’s start with User model:
public function viewedPosts() return $this->belongsToMany(Post::class, 'user_post_views') ->withTimestamps() ->withPivot(['count', 'id']);
The withTimestamps() method will ensure that the created_at andupdated_at timestamps are automatically maintained at the pivot table. We are also grabbing the count and id fields from the pivot table because later we need to increment this.
Now let’s define the inverse relationship on our Post model:
public function viewedUsers() return $this->belongsToMany(User::class, 'user_post_views') ->withTimestamps() ->withPivot(['count']);
Here also we are grabbing the count field from the pivot table. We will later use this to sum up the number of times a particular post has been viewed by different users.
# Dispatching a job from the controller
Now that we have the relationship and pivot table setup between our models, let’s work on logging a view. Say we have this route to view a post:
Route::get('/posts/post', 'PostController@show')->name('posts.show');
Of course we can write the entire logging logic within the show() method onPostController , but a more flexible way would be to create a job and dispatch it every time a user views a post. In this way we not only separate the logging logic from the controller and keep it slim, but going forward we can even implement queuing on this.
So let’s create a job, say UserViewedPost . Now in the show() method, we can quickly dispatch() it before rendering the requested post.
public function show(Request $request, Post $post) if($request->user()) dispatch(new UserViewedPost($request->user(), $post)); return view('posts.show', compact('post'));
We first ensure that a user is currently signed in. We then dispatch the UserViewedPost job and pass the currently signed in user and the post into the job’s constructor. Finally we render a view with that post.
# Logging recent views
Now that we are dispatching UserViewedPost job from the PostController , let’s log the view.
First let’s accept the models that were passed into the job’s constructor.
public $user; public $post; public function __construct(User $user, Post $post) $this->user = $user; $this->post = $post;
We are keeping the $user and $post properties as public, because we may want to queue this job later.
Next, in the handle() method, we first want to check if this user has already viewed this post. In case he has already viewed it, we do not need to create a new entry as we can simply increment the count from the previous entry.
// this user has already viewed this post if($this->user->viewedPosts->contains($this->post)) $this->user->viewedPosts->where('id', $this->post->id) ->first() ->pivot ->increment('count'); return;
$this->user->viewedPosts is used to access the relationship betweenUser and Post . This will return a collection of posts this user has viewed. Thecontains($this->post) will determine if the collection already contains this post. If it does, we search for this post where(‘id’, $this->post->id) in the collection, grab the first() entry, then access the pivot and increment thecount .
However, if this user has not viewed this post earlier, we want to create a new record for this in our pivot table.
// this user is viewing this post for the first time $this->user->viewedPosts()->attach($this->post, [ 'count' => 1 ]);
Because we are working with many to many relationship, we can simply access this user’s viewed posts $this->user->viewedPosts() and attach() this post to this user. We also want to initialize our view count. The attach() method also takes an array of additional data, so we can pass the initial count into this method attach($this->post, [‘count’ => 1]) .
That’s all we need to log views. The complete handle() method is as follows:
public function handle() // this user has already viewed this post if($this->user->viewedPosts->contains($this->post)) $this->user->viewedPosts->where('id', $this->post->id) ->first() ->pivot ->increment('count'); return; // this user is viewing this post for the first time $this->user->viewedPosts()->attach($this->post, [ 'count' => 1 ]);
The handle() method is called whenever the job is processed. We can also queue this job. Laravel documentation provides a detailed explanation of setting up queues.
# Fetching the recently viewed posts
Now that the views are being logged, we want to show the users a list of their recently viewed posts.
Say we have a route like this:
Route::get('/posts/recent', 'PostController@recentlyViewedPosts') ->name('posts.recent') ->middleware('auth');
Because we have the necessary relationship setup, fetching these records are very easy.
public function recentlyViewedPosts(Request $request) $posts = $request->user()->viewedPosts() ->orderBy('pivot_updated_at', 'desc') ->take(5) ->get(); return view('posts.recent', [ 'posts' => $posts ]);
We get the request object and from that request, we extract the currently signed in user and accessing the relationship, we query for all the posts this user has viewed, $request->user()->viewedPosts() , sort the result byupdated_at field and take() the last 5 posts. In the orderBy() method, we are using pivot_updated_at to sort the posts by using the time they were last viewed. If we just use updated_at instead, it will use the time when the posts were last edited and not the time when they were inserted or incremented in the pivot, which we do not want. Lastly, we go ahead and render a view.
Notice that we are hardcoding the number of posts in the take() method. If you want to mention the number of posts you are showing in your view, you have to again hardcode it. This is usually not a good practice. A better way is to create a limiting constant, say const POST_LIMIT = 5; and then use it like this: take(self::POST_LIMIT) . You can then pass this constant to your views and use it. This way refactoring becomes easy.
# Calculating total views of a post
To calculate the total views of a post, we will use the reverse relationship we setup in our Post model.
public function views() return array_sum($this->viewedUsers->pluck('pivot.count')->toArray());
Remember we have set this as a many to many relationship. That means, each post has many users who may have viewed it. Therefore, using the reverse relationship, we create a collection of users $this->viewedUsers who have viewed this post. Using the pluck() method, we then pluck out the count from the pivot table , which gives us a collection of the number of times any user has viewed this particular post. The toArray() method then converts the collection to an array and we use array_sum() to sum up all the values.
Now in our views, we can use $post->views() to show the number of times a post has been viewed.
# Conclusion
There are a couple of things we have not addressed here:
First, the view counter only works for signed in users. If an user is not signed in, but viewing a post, that view will not be added to the total number of views. Of course you can go ahead and tweak this code to increment the count regardless of the user is signed in or not.
Second, we have not implemented view throttling. What we are doing here is that if a signed in user keeps loading a post, the view count will keep on increasing. You may want to limit this count hourly or daily, i.e. if a user views a post multiple times within an hour, view count will be incremented only once. An excellent blog post on view throttling, written, can be found here.
Happy coding…
0 notes
Text
Which Are Some Of The Most Popular Back End Frameworks?
New Post has been published on http://zeroduedesign.co.uk/blog/feed/which-are-some-of-the-most-popular-back-end-frameworks/
Which Are Some Of The Most Popular Back End Frameworks?
Nowadays, the user experience delivered by an application determines its popularity and profitability in the longer run. Hence, it becomes essential for developers to focus on both front-end and back-end of the application. Normally, the users can see, touch and experience the front-end or user interface of the application directly.
But the front-end experience of an application is driven by various aspects of its backend – database interactions, business logic, user request processing, and performance. Hence, the developers frequently explore ways to enhance the performance and quality of the backend code. Most developers take advantage of robust back-end frameworks to make the applications deliver optional user experience without putting extra time and effort.
Brief Overview of 12 Widely Used Back-end Web Frameworks
1) ASP.NET Core
Microsoft recently released ASP.NET Core 1.0 with several innovative features to simplify development, testing, and deployment of both web and cloud application. In addition to being an open source web application framework, ASP.NET Core supports three distinct platforms- Windows, OS X and Linux. Also, it allows developers to deploy their applications in a number of ways. The developers have option to integrate ASP.NET Core with several open source web development tools, while taking advantage of a robust integrated development environment (IDE) like Visual Studio.
2) Ruby on Rails
Ruby on Rails (RoR) is a widely used web application framework for Ruby programming languages. It supports several widely used software development paradigms including MVC, and emphasizes on software testing. The plug-and-play functionality provided by RoR enables developers to customize the web application according to varying business requirements. The programmers can further take advantage of the code library and scaffolding options provided by RoR to accomplish common web development tasks without writing additional code. They can further use RoR to create prototype of the application, and move from planning to development phase of the project quickly.
3) Django
Django is a hugely popular Python web application framework. Python enables developers to build web applications with concise, readable and reusable code. Also, Django supports MVC design pattern. Hence, the developers can keep the business logic, user interface and application data separate. At the same time, they can take advantage of the built-in tools provided by Django to accomplish common web development tasks like site maps, user authentication, content administration, and memcaching. Django further allows programmers to customize individual parts of the web application according to specific business requirements. Also, it provides several packages, along with a robust ORM system, and a dynamic admin interface.
4) Node.js
The JavaScript library enables web developers to write server-side code in JavaScript. Many developers use Node.js to write both client-side and server-side code in JavaScript. Node.js is also used widely by developers as part of MEAN Stack along with MangoDb, Elegant.js and AngularJS. However, Node.js is designed as a cross-platform runtime engine, and executes code through Google’s V8 JavaScript engine. It further enhances the execution speed of JavaScript code by executing commands in parallel through non-blocking functions and allowing programmers to run operations asynchronously. At the same time, Node.js comes with features to simplify common web development tasks like file system I/O, data streaming, binary data and networking.
5) Play Framework
The open source web application framework is written in Scala. It enables developers to build feature-rich web applications by combining Java and Scala programming languages. As Play supports MVC design pattern, it becomes easier for developers to simplify web application development by keeping business logic and user interface layers separate. Also, the non-blocking and stateless architecture of Play Framework enables developers to scale web applications without putting extra time and effort. The developers can further assess the quality of the code continuously by availing the built-in testing support and just hit refresh workflow of the Scala web framework.
6) Catalyst
Catalyst is a widely used Perl web framework. As it supports MVC principle, it becomes easier for developers to build and maintain large web applications by keeping their user interface and business logic layers separate. Also, the developers can avail the ready-to-use plug-ins provide by Catalyst to accomplish a variety of web development tasks like user authentication, caching, and session management. Catalyst further comes with a lightweight test server and a robust database ORM, while supporting multiple templating languages. The Perl web framework is further designed with features to keep common development tasks simple and clean.
7) Laravel
The PHP framework enables developers to accomplish common tasks like authentication, session management, routing and caching by writing expressive code. It further provides a variety of tools to speed up development of large and complex web applications. Also, it makes it easier for programmers to conduct unit test to assess the impact of changes made to the code at various stages of development. Laravel also comes with a template engine called Blade that allows programmers to reduce performance overheads by writing plain PHP code in the templates. The version 5.3 of Laravel further comes with a number of new features like simplified API authentication and option to add WebSockets to the application.
8) Phalcon
Phalcon is a modern PHP framework which is designed with focus on speed. Unlike other frameworks, Phalcon is a PHP extension written in C programming language. So it consumes lower resources while delivering optimized performance. As Phalcon is loosely coupled, the programmers have option to use the framework fully or its specific parts as glue components. They can further download and install the framework as a PHP module. Phalcon further provides features to accomplish common tasks like database access, authentication, transaction, messaging, caching, queuing, template engine, form builder, and routing.
9) Symfony
Symfony comes with an array of features that help programmers to create and maintain PHP web applications without putting extra time and effort. It enables developers to add functionality to the website by adding a variety of prefabricated components. At the same time, it also allows them to use third-party software components. Thus, it becomes easier for programmers to enhance the website’s functionality and performance by adding a variety of software components. The users also have option to perform unit testing by using popular frameworks like PHPUnit. They also have option to speed up development of complex application by using the full-stack version of the framework.
10) Yii Framework
Yii is one of the high-performance PHP frameworks available in the market. As it supports MVC pattern, it becomes easier for programmers to reduce the development time by keeping the business logic and user interface separate. At the same time, they can easily boost the application’s performance by availing powerful caching support provided by Yii. Yii further helps developers to work with AJAX more efficiently. It further makes user input collection through forms more secure by providing validators, widgets and helper methods. Also, it comes with features to protect the application from SQL injection and cross-site scripting attacks. The developers can further use Yii to perform unit tests and functionality testing without putting any extra time and effort.
11) CakePHP
The PHP framework comes with features to help programmers to create prototypes and build applications rapidly. The developers can avail the code generation feature of CakePHP to create prototypes of the application easily. At the same time, they can further avoid writing longer lines of code by availing built-in features for database access, authentication, validation, translation, and caching. The users can further start using CakePHP simply after setting the database up. CakePHP further guides programmers to handle all aspects of the application efficiently, while supporting MVC design pattern.
12) Zend Framework 2
Along with being a mature PHP framework, Zend is also being used by several large websites. The open source framework enables programmers to create websites by using object-oriented code. The modular structure of Zend further makes it easier for users to combine its building blocks with other frameworks and libraries. As Zend is designed a collection of classes, the programmers can load the required components as individual libraries. Also, they can use ZendService to access popular web services by implementing client-side libraries. However, many programmers feel that Zend has a more difficult learning curve. Zend still comes with features to speed up development of large-scale web applications.
On the whole, the web application developers have option to choose from a wide range of back-end web frameworks. But the smart developers always opt for a back-end framework that complements preferred programming language and meets all needs of the project. The developers must evaluate the pros and cons of each framework according to their skills and needs.
Source
0 notes
Photo

New Post has been published on http://programmingbiters.com/save-laravel-app-settings-in-database/
Save laravel app settings in database
I this post I am going to share one feature which most of the application have these days to change certain settings using UI, it can be implemented in many ways but one way I find doing is to store settings in the database and provide an auto-generated form to change the settings.
What are we building?
We will be building a setting management system which will be easily customizable and you can use it in any app you want to give the option to change the settings on the fly using a form UI.
Source Code
We will create a config file where we can define all the options you want to give the user as settings. Then we will create a route which will show the defined option from the config file in a form, upon hitting save settings we will update it in the database.
Next, we will be adding a helper function
setting($key, $default = null)
to access the stored settings.
Create Laravel App
Let’s start by creating a brand new application in laravel 5.5.
composer create-project --prefer-dist laravel/laravel db-settings
Once it’s installed we need auth scaffolded, run
php artisan make:auth
to generate scaffolding, before migrating make sure you have configured database. add your credentials in .env file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=dbsetting DB_USERNAME=root DB_PASSWORD=secret
Now run the
php artisan migrate
it will create the tables for migration and give you auth routes setup. Go ahead and register a new user and login.
Settings model and migration
To store settings in the database we need a table with 3 fields:
name: unique name string used as a key for settings val: value of the setting, it will be a text column type: date type will be used to cast the value to
string
,
integer
or
boolean
etc.
Run
php artisan make:model Setting -mc
to create the migration and controller for same. Edit the settings migration file in database/migrations and add above columns:
public function up() Schema::create('settings', function (Blueprint $table) $table->increments('id'); $table->string('name'); $table->text('val'); $table->char('type', 20)->default('string'); $table->timestamps(); );
That’s it for migration, let’s move on to the settings config file, we will get back to
Setting
model to implement all the functionality later.
Create setting_fields in Config
We have our laravel installation, let’s create a config file
config/setting_fields.php
and add the following array.
return [ 'app' => [ 'title' => 'General', 'desc' => 'All the general settings for application.', 'icon' => 'glyphicon glyphicon-sunglasses', 'elements' => [ [ 'type' => 'text', // input fields type 'data' => 'string', // data type, string, int, boolean 'name' => 'app_name', // unique name for field 'label' => 'App Name', // you know what label it is 'rules' => 'required|min:2|max:50', // validation rule of laravel 'class' => 'w-auto px-2', // any class for input 'value' => 'CoolApp' // default value if you want ] ] ], 'email' => [ 'title' => 'Email', 'desc' => 'Email settings for app', 'icon' => 'glyphicon glyphicon-envelope', 'elements' => [ [ 'type' => 'email', ... ], [ ... ], [ ... ] ] ], ]
If you see the above array we have defined our settings into sections, first top-level element in the array is
app
, and under this, we have its meta information like
title
and
description
, the main part is the elements array, it defines all the input fields needed as form input elements.
Setting Model
This is the backbone of settings, we will add some methods on this model which will give a similar API as laravel config does, for example, you will be able to call
Setting::set('key', 'value')
to set a value in settings and
Setting::get('key')
to get a setting value.
use IlluminateSupportCollection; use IlluminateDatabaseEloquentModel; class Setting extends Model int */ private static function castValue($val, $castTo) switch ($castTo) case 'int': case 'integer': return intval($val); break; case 'bool': case 'boolean': return boolval($val); break; default: return $val; /** * Get all the settings * * @return mixed */ public static function getAllSettings() return self::all();
That’s lots of code, everything is self-explanatory, you can see I am getting all the settings stored in the database, and from
getDefinedSettingFields()
method accessing
setting_fields
config as a collection object, Next am plucking
default value
validation rules
,
casting type
, values for form input field.
Settings Route
We can now move on to setting the route for our settings page, let’s add it
routes/web.php
.
Route::get('/home', 'HomeController@index')->name('home'); Route::group(['middleware' => 'auth'], function () Route::get('/settings', 'SettingController@index')->name('settings'); Route::post('/settings', 'SettingController@store')->name('settings.store'); );
Settings Controller
The Controller will have two methods, index and store. run
php artisan make:controller SettingController
to create it, now open and add this.
public function index() return view('setting.index'); public function store(Request $request) $rules = Setting::getValidationRules(); $data = $this->validate($request, $rules); $validSettings = array_keys($rules); foreach ($data as $key => $val) if (in_array($key, $validSettings)) Setting::add($key, $val, Setting::getDataType($key)); return redirect()->back()->with('status', 'Settings has been saved.');
Index method is pretty simple, it just returns a view, store method handles actual database persistence logic, It gets the validation rules from config by
Setting::getValidationRules()
, then it just loops over the request data and adds it in setting if a setting is defined in config file.
Our
Setting::add($key)
method first checks if setting with the name already exists, if yes it simply updates it otherwise it creates a new setting with given key.
Settings View
Now we can focus on rendering all the fields defined in
config/setting_fields.php
I will use a bootstrap panel for each section, and inside this panels body we will loop over all the fields from
elements
array.
Create a new view
resources/views/setting/index.blade.php
and add following markup:
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> @if (session('status')) <div class="alert alert-success"> session('status') </div> @endif <form method="post" action=" route('settings.store') " class="form-horizontal" role="form"> !! csrf_field() !! @if(count(config('setting_fields', [])) ) @foreach(config('setting_fields') as $section => $fields) <div class="panel panel-info"> <div class="panel-heading"> <i class=" array_get($fields, 'icon', 'glyphicon glyphicon-flash') "></i> $fields['title'] </div> <div class="panel-body"> <p class="text-muted"> $fields['desc'] </p> </div> <div class="panel-body"> <div class="row"> <div class="col-md-7 col-md-offset-2"> @foreach($fields['elements'] as $field) @includeIf('setting.fields.' . $field['type'] ) @endforeach </div> </div> </div> </div> <!-- end panel for $fields['title'] --> @endforeach @endif <div class="row m-b-md"> <div class="col-md-12"> <button class="btn-primary btn"> Save Settings </button> </div> </div> </form> </div> </div> </div> @endsection
Everything is basic HTML in a loop, but notice this part:
@foreach($fields['elements'] as $field) @includeIf('setting.fields.' . $field['type'] ) @endforeach
I have extracted all the fields type in there own partials, it keeps your views clean and maintainable, we could have used if and else handle this rendering but keeping it in separate view partials make it a lot easier to organize. And you can add as many types as you want, you just need to define an element in config with ‘type’ => ‘datepicker’ or anything and create a partial in
resources/views/setting/fields/datepicker.blade.php
to handle all the rendering in this file.
Now lets see how a fileds type view partials looks like:
Input type text view
<div class="form-group $errors->has($field['name']) ? ' has-error' : '' "> <label for=" $field['name'] "> $field['label'] </label> <input type=" $field['type'] " name=" $field['name'] " value=" old($field['name'], setting($field['name'])) " class="form-control array_get( $field, 'class') " id=" $field['name'] " placeholder=" $field['label'] "> @if ($errors->has($field['name'])) <small class="help-block"> $errors->first($field['name']) </small> @endif </div>
And as you know input type
email
,
number
,
date
etc are very similar, just change the type property on the element will give us the input type, for example, to allow input type email we just need to create a partial call
resources/views/setting/fields/email.blade.php
and inside it just add following:
Input Email view
@include('setting.fields._text')
And the same thing is for
number
,
date
etc.
Input Select view
Create another partial inside
fields/select.blade.php
and add following:
<div class="form-group $errors->has($field['name']) ? ' has-error' : '' "> <label for=" $field['name'] "> $field['label'] </label> <select name=" $field['name'] " class="form-control array_get( $field, 'class') " id=" $field['name'] "> @foreach(array_get($field, 'options', []) as $val => $label) <option @if( old($field['name'], setting($field['name'])) == $val ) selected @endif value=" $val "> $label </option> @endforeach </select> @if ($errors->has($field['name'])) <small class="help-block"> $errors->first($field['name']) </small> @endif </div>
As you can see its pretty easy to customize it, for example, if you want to change it to work with another frontend framework like
Bulma
,
Foundation
or
Tailwind CSS
you just need to change the markup and classes in fields partials.
Setting helper function
You might have noticed I have used
setting($key)
helper function to get the stored value for that key in the database. Let’s add this helper function in our composer autoload.
Open the composer.json and in autoload object add files array you want to autoload.
... "psr-4": "App": "app/" , "files": [ "app/Utils/helpers.php" ]
Next, create our helpers file in
app/Utils/helpers.php
and add this function:
if (! function_exists('setting')) function setting($key, $default = null) if (is_null($key)) return new AppSettingSetting(); if (is_array($key)) return AppSettingSetting::set($key[0], $key[1]); $value = AppSettingSetting::get($key); return is_null($value) ? value($default) : $value;
With that we have completed our settings management system, let’s serve the app and see, you should see the following screen with all the settings you defined, before hitting Save Settings you must migrate the database to create settings table.
Make some changes and hit Save Settings, check the database your settings will be saved, now you can access them anywhere in your application by calling
Setting::get('setting_name')
or our helper function
setting('setting_name')
.
But there is a problem, We are listing all settings and calling
setting('setting_name')
multiple times which is making one query to the database for each call 🙁 that’s a lot of queries to get the settings.
Let’s add caching in the Setting model to avoid multiple queries to the database. Modify the
getAllSettings()
method and add some more to handle the cache flushing etc.
/** * Get all the settings * * @return mixed */ public static function getAllSettings() return Cache::rememberForever('settings.all', function() return self::all(); ); /** * Flush the cache */ public static function flushCache() Cache::forget('settings.all'); /** * The "booting" method of the model. * * @return void */ protected static function boot() parent::boot(); static::updated(function () self::flushCache(); ); static::created(function() self::flushCache(); );
We are caching all settings from the database and returning it, then we hooked into model events,
created
,
deleted
and
updated
to flush the cache on any change so our settings will have updated value. It has solved multiple query issue.
I have used key ‘settings.all’, you should pic a unique key prefixed with some model ID for your app if your app offers settings based on user, team etc.
As always I have posted the complete source code for you on GitHub, have fun, implementing settings will be now a piece of cake, just change the definition in the config/setting_fields.php file and your settings page will reflect new fields 😎
Source Code
Related
0 notes