#timestamp laravel
Explore tagged Tumblr posts
korshubudemycoursesblog · 4 months ago
Text
Build Portfolio Website in Laravel 11: Your Comprehensive Guide
Building a portfolio website is an essential step for showcasing your skills, projects, and achievements in today's competitive world. Laravel 11, the latest version of the robust PHP framework, offers unparalleled tools and features to create a stunning and functional portfolio website. In this guide, we’ll walk you through the process of building a portfolio website in Laravel 11, ensuring you have a step-by-step roadmap to success.
Why Choose Laravel 11 for Your Portfolio Website?
1. Modern Features
Laravel 11 introduces enhanced routing, improved performance, and advanced tooling that make it the go-to choice for web development.
2. Scalability
Whether you're a freelancer or a business owner, Laravel 11's scalability ensures your website can grow as your portfolio expands.
3. Security
With built-in authentication and security features, Laravel 11 protects your data and provides peace of mind.
4. Community Support
Laravel’s vast community ensures you’ll find solutions to problems, tutorials, and plugins to enhance your website.
Key Features of a Portfolio Website
To build a portfolio website in Laravel 11, ensure it includes:
Homepage: A welcoming introduction.
About Section: Your background and expertise.
Projects: A gallery showcasing your work.
Contact Form: Easy communication.
Blog Section: Share insights and updates.
Responsive Design: Optimized for all devices.
Getting Started with Laravel 11
Step 1: Install Laravel 11
Start by setting up Laravel 11 on your local environment.
composer create-project --prefer-dist laravel/laravel portfolio-website
Step 2: Configure Your Environment
Update your .env file to set up the database and other environment variables.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=portfolio
DB_USERNAME=root
DB_PASSWORD=yourpassword
Step 3: Set Up Authentication
Laravel 11 offers seamless authentication features.
php artisan make:auth
This command generates routes, controllers, and views for user authentication.
Step 4: Design Your Database
Create tables for your portfolio items, such as projects, blogs, and user profiles. Use migrations to structure your database.
php artisan make:migration create_projects_table
In the migration file:
Schema::create('projects', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('description');
    $table->string('image')->nullable();
    $table->timestamps();
});
Run the migration:
php artisan migrate
Building the Frontend
Step 1: Choose a CSS Framework
Laravel integrates well with frameworks like Tailwind CSS and Bootstrap. Install Tailwind CSS for modern and responsive designs:
npm install -D tailwindcss
npx tailwindcss init
Configure your Tailwind file and integrate it into your project.
Step 2: Create Blade Templates
Laravel’s Blade templating engine simplifies building dynamic pages. Create a layout file in resources/views/layouts/app.blade.php:
<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
</body>
</html>
Use this layout in other views:
@extends('layouts.app')
@section('title', 'Home')
@section('content')
<h1>Welcome to My Portfolio</h1>
@endsection
Step 3: Dynamic Content
Fetch portfolio items from the database and display them dynamically using controllers.
public function index() {
    $projects = Project::all();
    return view('home', compact('projects'));
}
In your Blade template:
@foreach ($projects as $project)
<div class="project">
    <h2>{{ $project->title }}</h2>
    <p>{{ $project->description }}</p>
    <img src="{{ $project->image }}" alt="{{ $project->title }}">
</div>
@endforeach
Advanced Features
1. Search Functionality
Add search to help visitors find specific projects or blogs.
public function search(Request $request) {
    $query = $request->input('query');
    $projects = Project::where('title', 'LIKE', "%{$query}%")->get();
    return view('search-results', compact('projects'));
}
2. File Uploads
Enable uploading images for projects.
public function store(Request $request) {
    $request->validate([
        'title' => 'required',
        'description' => 'required',
        'image' => 'nullable|image',
    ]);
    $imagePath = $request->file('image')->store('projects', 'public');
    Project::create([
        'title' => $request->title,
        'description' => $request->description,
        'image' => $imagePath,
    ]);
}
3. Integrate Analytics
Use Google Analytics or similar tools to track visitor behavior.
4. Deploying Your Website
Deploy your Laravel website using platforms like Laravel Forge, AWS, or Heroku. Ensure to optimize the performance with caching and minification.
Optimizing Your Portfolio Website for SEO
Keyword Integration: Use keywords like “Build Portfolio Website in Laravel 11” strategically in titles, meta descriptions, and content.
Fast Loading Times: Optimize images and use caching.
Responsive Design: Ensure compatibility with mobile devices.
Content Strategy: Regularly update your blog to attract organic traffic.
Conclusion
Building a portfolio website in Laravel 11 is an enriching experience that showcases your skills and work to the world. By leveraging the framework’s capabilities and integrating advanced features, you can create a website that stands out in the digital landscape. Start your journey today and make your mark with a professional portfolio website
0 notes
kevinsoftwaresolutions · 1 year ago
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.
Tumblr media
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
excellisit · 1 year ago
Text
Building Chat Applications with Laravel Echo: A Guide to Real-Time Interactivity
In the ever-evolving landscape of web development, the demand for real-time communication features has surged, giving rise to the need for robust and efficient solutions. Laravel Echo, a powerful tool integrated into the Laravel framework, emerges as a key player in facilitating real-time interactions, particularly in the realm of chat applications. A leading web development company in Kolkata provides professional services on building chat applications with Laravel Echo. 
Tumblr media
In this comprehensive guide, we'll explore the fundamentals of Laravel Echo, its integration with Laravel Broadcasting, and how developers can leverage this dynamic duo to build engaging and responsive chat applications.
Understanding Laravel Echo and Broadcasting
Laravel Echo: The Voice of Real-Time Web Applications
Introduction to Laravel Echo:
Laravel Echo is a JavaScript library that simplifies the implementation of real-time features in web applications. It serves as the bridge between your Laravel back end and the front end, allowing seamless communication and data synchronization.
Features and Benefits:
Event Listening: Laravel Echo enables the listening for specific events broadcasted by the server, such as new messages or user updates.
Broadcasting Channels: It provides a straightforward way to subscribe to and broadcast events on channels, facilitating organized communication.
WebSocket Integration: Laravel Echo seamlessly integrates with WebSocket protocols, ensuring low-latency, real-time updates.
Laravel Broadcasting: Broadcasting Events to Multiple Clients
Introduction to Laravel Broadcasting:
Laravel Broadcasting is the Laravel framework's built-in solution for real-time event broadcasting. It utilizes various broadcasting drivers, including Pusher, Redis, and more, to broadcast events to multiple clients simultaneously.
Event Broadcasting Workflow:
Event Creation: Define events that should trigger real-time communication, such as a new chat message or user activity.
Event Broadcasting: Laravel Broadcasting broadcasts these events to subscribed clients through a selected broadcasting driver.
Client-Side Listening: Laravel Echo on the client side listens for these events, triggering actions based on the received data.
Building a Real-Time Chat Application with Laravel Echo
Unveiling the synergy of Laravel Echo and Laravel Broadcasting, this guide empowers developers to craft engaging chat experiences that transcend traditional communication boundaries. 
From setting up real-time events to implementing presence channels and optimizing the chat interface, join us in exploring the intricacies of Laravel Echo as we bring the immediacy of real-time interactions to the forefront of web development.
Setting Up Laravel Broadcasting: 
Installation and Configuration
Install Laravel Echo and a broadcasting driver of your choice (e.g., Pusher, Redis).
Configure Laravel to use the chosen broadcasting driver in the broadcasting.php configuration file.
Creating Chat Events
Event Creation:
Generate an event class for chat messages using the php artisan make:event command.
Define the necessary properties within the event class, such as the sender, message content, and timestamp.
Broadcasting the Event:
Implement the ShouldBroadcast interface in the event class to indicate that it should be broadcast.
Laravel automatically handles broadcasting the event when triggered.
Broadcasting Chat Messages
Server-Side Broadcasting:
When a new chat message is created, broadcast the chat event using Laravel's event system.
Laravel Broadcasting takes care of pushing the event data to the selected broadcasting driver.
Client-Side Listening:
On the client side, use Laravel Echo to listen for the chat event.
Define actions to take when the event is received, such as updating the chat interface with the new message.
Implementing Presence Channels
Introduction to Presence Channels:
Presence channels in Laravel allow you to track the presence of users in real-time.
Useful for displaying online users, typing indicators, or other presence-related features in a chat application.
Setting Up Presence Channels:
Define presence channels in Laravel Echo and configure the back end to authorize users to join these channels.
Update the front end to display real-time presence information.
Optimizing and Enhancing the Chat Experience
Discover how to seamlessly integrate real-time features, implement presence channels, and employ innovative strategies. It helps developers create a dynamic and immersive chat environment that goes beyond conventional expectations, providing users with an enriched and interactive communication experience.
Authentication and Authorization
User Authentication:
Authenticate users within your Laravel application.
Laravel Echo automatically binds the authenticated user's ID to the broadcasted events.
Authorization for Channels:
Implement channel authorization to ensure that users can only access channels they are authorized to join.
Laravel Echo provides mechanisms to handle this authorization seamlessly.
Implementing Typing Indicators
Real-Time Typing Notifications:
Extend the chat application by implementing real-time typing indicators.
Broadcast typing events when users start or stop typing, updating the interface for all connected users.
Storing and Retrieving Chat History
Database Integration:
Store chat messages in the database to ensure persistence and enable retrieval of chat history.
Implement methods to fetch and display chat history on the client side.
Security Considerations
Secure Broadcasting:
Implement secure practices, such as using HTTPS and securing broadcasting channels, to ensure the confidentiality and integrity of transmitted data.
Data Validation:
Implement robust validation for incoming chat messages to prevent security vulnerabilities.
Conclusion: Elevating Interactivity with Laravel Echo
In conclusion, Laravel Echo emerges as a game-changer for developers seeking to enhance their web applications with real-time interactivity. Whether you're building a chat application, collaborative tools, or live update features, Laravel Echo, in tandem with Laravel Broadcasting, provides a seamless and efficient solution. By following the outlined steps and considerations, developers can empower their applications with the dynamic responsiveness users crave in today's digital landscape. A leading web development company in Kolkata also helps build chat applications with Laravel Echo. Laravel Echo opens the door to a new era of user engagement, where real-time communication is not just a feature but a cornerstone of modern web development.
0 notes
Link
Laravel developed by Taylor Otwell, is a powerful MVC PHP framework. It is designed for developers who require a smart and simple toolkit to build full-featured web apps.A user can do many interesting things with laravel timestamp. Want to learn some timestamp tricks in Laravel.
2 notes · View notes
codehunger · 4 years ago
Text
Laravel-find days between two dates in laravel
Laravel-find days between two dates in laravel
In this blog, we will learn about how to find days between two dates in laravel, This tutorial will give you a simple example of getting days difference in laravel. if you want to see an example of how to get days difference in laravel then you are in the right place. Follow the below tutorial step of laravel 8 gets last week’s records from the database. If you want to see what all carbon does…
Tumblr media
View On WordPress
1 note · View note
ineedbreadflour-blog · 5 years ago
Text
My Own Blog by Laravel(1)
Make my own blog with Laravel!!
Hi guys, I will make my own blog by Laravel. I'm a Japanese cook in BC. But I don't work now because of COVID-19. So I have much time now. That's why I have started to learn Laravel. I'm not a good English writer. But I will do my best in English. Please correct my English if you would notice any wrong expressions. Thank you!
Anyway, I will post about making a blog by Laravel for a while. Let's get started!
All we have to do
Install Laravel
Create a Project
Database Setting
Migration
Create Models
Seeding
Routing
Make Controllers
Make Views
Agenda
Today's agenda is
Install Laravel
Create a Project
Database Setting
Migration
Create Models
Seeding
Install Laravel
Laravel utilizes Composer to manage its dependencies. So install Composer first if you have not installed Composer yet. Ok, now you can install Laravel using Composer.
% composer global require Laravel/installer
Here we go. So next step is to create a project named blog!
Create a project
Creating a project in Laravel is super easy. Just type a command like below.
% laravel new blog
That's it. So easy. That command bring every dependencies automatically. And you move to blog directory.
% cd blog
Now you can use a new command called 'artisan'. It's a command used for Laravel. For example, you can start server with this command.
% php artisan serve
Do you see command line like this?
% php artisan serve ~/workspace/blog Laravel development server started: http://127.0.0.1:8000 [Mon Apr 20 09:20:56 2020] PHP 7.4.5 Development Server (http://127.0.0.1:8000) started
You can access localhost:8000 to see the Laravel's welcome page! If you want to know the other arguments of artisan, just type like this.
% php artisan list
Then you can see all artisan commands. You can also display the commands for a specific namespace like this.
% php artisan list dusk ~/workspace/blog Laravel Framework 7.6.2 Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --env[=ENV] The environment the command should run under -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug Available commands for the "dusk" namespace: dusk:chrome-driver Install the ChromeDriver binary dusk:component Create a new Dusk component class dusk:fails Run the failing Dusk tests from the last run and stop on failure dusk:install Install Dusk into the application dusk:make Create a new Dusk test class dusk:page Create a new Dusk page class
So let's go to next step!
Database setting
Open .env located under root directory. And edit around DB setting.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=blog DB_USERNAME=root DB_PASSWORD=
Depends on your database. I use MySQL and I already create database named blog in MySQL. You should create user for only this project when you deploy.
Migration
Laravel supplies the migration system. It allow you to control database using php code. For example, when you want to create database, type the command like this.
% php artisan make:migration create_posts_table
You can see a new migration file database/migrations/xxxx_xx_xx_xxxxxx_create_posts_table.php. Write down columns you need in the function called up() and write down columns you want to delete in down(). Edit it.
public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->boolean('published'); $table->string('title'); $table->longText('body'); $table->string('tag')->nullable(); $table->timestamps(); }); }
It's ready! Execute this command.
% php artisan migrate
Here we go! Now you got some tables with columns! Let's check them out in MySQL console.
% mysql -uroot
And check tables and columns.
mysql> use blog; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> show tables; +----------------+ | Tables_in_blog | +----------------+ | failed_jobs | | migrations | | posts | | users | +----------------+ 4 rows in set (0.01 sec) mysql> desc posts; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | published | tinyint(1) | NO | | NULL | | | title | varchar(191) | NO | | NULL | | | body | longtext | NO | | NULL | | | tag | varchar(191) | YES | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | | user_id | int(11) | NO | MUL | NULL | | +------------+------------------+------+-----+---------+----------------+ 8 rows in set (0.01 sec)
Good! You could create tables and columns by php. Next step is Create Model.
Create Model
Laravel Framework is MVC application model. MVC is Model, View and Controller. Application works with each role. View works for display to browsers. Controller works as a playmaker. It receives request from router and access databases to get some datas and pass the datas to views. Model connects to the database and gets, inserts, updates or deletes datas.
Now you create a Model.
% php artisan make:model Post
Then you will see the new Post model under app/Post.php.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { // }
This model has no code. But it's ok. You can leave it for now.
About a model name
A model name is important. A model connects to table of the database with the rule of the name. If you have a posts table, Post model is mapped with posts table automatically.
Seeding
Seeding is very useful function for preparing test datas or master datas. You can use it easily. All you need is just 1. making seeder file and 2. executing it. Let's do that.
Making seeder files
% php artisan make:seeder BooksTableSeeder Seeder created successfully.
Edit seeder files
public function run() { DB::table('posts')->truncate(); $posts = [ [ 'published' => true, 'title' => 'The First Post', 'body' => '1st Lorem ipsum...', 'tag' => 'laravel', 'user_id' => 1 ], [ 'published' => true, 'title' => 'The Second Post', 'body' => '2nd Lorem ipsum dolor sit amet...', 'tag' => 'shiba-inu', 'user_id' => 1 ], [ 'published' => false, 'title' => 'The Third Post', 'body' => '3rd Lorem ipsum dolor sit ...', 'tag' => 'laravel', 'user_id' => 1 ] ]; foreach($posts as $post) { \App\Post::create($post); } }
And edit DatabaseSeeder.php file.
public function run() { // $this->call(UserSeeder::class); $this->call(PostsTableSeeder::class); }
Execute seegding
% php artisan db:seed Seeding: PostsTableSeeder Database seeding completed successfully.
Sweet. Let's check out database.
mysql> select * from posts; +----+-----------+-----------------+-----------------------------------+---------------------------------+---------------------+---------+ | id | published | title | body | tag | created_at | updated_at | user_id | +----+-----------+-----------------+-----------------------------------+-----------+---------------------+---------------------+---------+ | 1 | 1 | The First Post | 1st Lorem ipsum... | laravel | 2020-04-19 19:16:18 | 2020-04-19 19:16:18 | 1 | | 2 | 1 | The Second Post | 2nd Lorem ipsum dolor sit amet... | shiba-inu | 2020-04-19 19:16:18 | 2020-04-19 19:16:18 | 1 | | 3 | 0 | The Third Post | 3rd Lorem ipsum dolor sit ... | laravel | 2020-04-19 19:16:18 | 2020-04-19 19:16:18 | 1 | +----+-----------+-----------------+-----------------------------------+-----------+---------------------+---------------------+---------+ 3 rows in set (0.00 sec)
Perfect! Now we can go next step!
So, see you next time!
References
Installation - Laravel - The PHP Framework For Web Artisans
1 note · View note
decodewebin · 5 years ago
Text
Json and Laravel Eloquent with example
JSON is short form of JavaScript Object Notation, which is used to store data and since it is very lightweight hence majorly used for transporting data to and from a web server. In earlier days, XML was used for this very purpose but writing and reading XML data was very tedious while JSON on the other hand, is self describing.
In today’s topic I am going to show you how to store JSON data into MySQL and access those data using laravel eloquent query builders.
Storing JSON data in MySQL using Laravel
First let’s create a dummy table using migration command.
Schema::create(json_examples, function (Blueprint $table) {             $table->bigIncrements('id');             $table->string('name');             $table->text('json_details'); //using text datatype to store json             $table->timestamps();         });
As you can see I used text datatype for storing json.
Next, let’s create a corresponding Model for the same
php artisan make:model JsonExample
JsonExample.php
public static function create($data) {     $new = new self();     $new->name = $data['name'];     $new->json_details = $data['json_details''];     $new->save(); }
So in controller we can do something like this:
public function storeEmpData(Request $request) {     ...     $name = $request->name';     $details = ['emp_code' => '001', 'date_of_joining' => Carbon::parse($request->doj), 'salary' => '50000'];         $dataToStore = [         'name' => $name,         'Json_details' => json_encode($details)       ];       //saving data       JsonExample::create($dataToStore); }
Processing Json data in Laravel eloquent.
Json data in where()
We can easily apply conditions on json data in laravel using -> (arrow notation), for example, fetch records where salary is more than 50000.
JsonExample.php
public static function getSalaryMoreThan($salary) {     return self::where('json_details->salary','>',$salary)->get(); }
Access json data using json_extract()
Another example, we need records of employees who joined the company before a date for instance 9th November 2018.
JsonExample.php
public static function getEmployeesBeforeDate($date) {     return self::whereDate("json_extract('json_details', '$.doj')", '<', $date)->get() }
As you can see above, I used json_extract() method which is MySQL’s function to extract a field from JSON column since I can not simply instruct eloquent using arrow operator like
return self::whereDate('json_details->doj', '<', $date)->get()
Rather I have to explicitly tell eloquent to extract json field and then proceed.
JSON data in DB::raw()
Many times we need to use MySQL’s aggregate functions like SUM() as per the requirement, in that case we use DB facade. For example,
select(DB::raw('sum(...)'))
How to access json field in MySQL’s aggregate function ?
It is very simple, let’s take an example, we need to sum total salary of employees.
public static function findTotalSalary() {     return self::select(DB:raw('sum("json_extract('json_details', '$.salary')") as total_salary'))->get(); }
Conclusion
That’s all about this topic friends, I hope you learned something new which you haven’t thought about. I thought I should share this knowledge as I encountered such problem while working on a project today where I do save additional data in json format. Do comment your reviews and experiences below.
Thank you :)
Ebooks available now
You can download this article’s PDF eBooks for offline reading from below:
Issuu
Slide Share
Edocr
AuthorStream
Scribd
4 notes · View notes
onclickonload · 6 years ago
Link
Tumblr media
2 notes · View notes
techrish · 2 years ago
Text
Best Tools for Laravel Development
PHPSTORM:
The best IDE for the Laravel framework is PHPStorm. PHPStorm is easy to use, with intelligent code navigation, quick and safe refactoring, simple debugging, and unit testing. It's also useful as a PHP code formatter.
While debugging codes saves time, learning how to code is essential for becoming a successful developer. Because of its high performance, many developers prefer PHPStorm.
Bitbucket:
The most popular Git services are GitHub and BitBucket. They both perform the same functions, but there are some distinctions. Use BitBucket if you're working on a Laravel-based project for a small business.
BitBucket is a good choice for people with a small number of collaborators who require private repositories. The various plans all provide unlimited access to private repositories, but the free plan only allows for five collaborators. GitHub, on the other hand, is a better choice for people working on open source projects because it allows for an unlimited number of collaborators.
It is simple to pull and push the source code, and it automatically combines the code with modifications and timestamps.
Laravel Debug bar:
When it comes to application debugging, Laravel shines. The debug bar in Laravel is to blame for all of this. It displays information about the debug mode when you click it at the bottom of the browser. You can see how many queries have been fired in the debugger's queries tab.
The template's output and parameters are shown. The developer can also see that the Façade option for adding messages will be available under the 'Message' tab of this debugger.
Laravel Forge:
Laravel Forge is a PHP server automation Laravel tool for preparing your web application for deployment. Among its notable features are security by default, database backups that install SSL certificates in seconds, easily set up required SSH keys, free SSL certificates, and so on.
Techrish Solutions - Laravel Development Company in UK
0 notes
scratch-coding · 2 years ago
Text
0 notes
codingspoint · 2 years ago
Text
How To Update a Record Without Updating Timestamp ?
How To Update a Record Without Updating Timestamp ?
Hello dev’s , today now in this article i will provide you some of the most important example of laravel update record without any update timestamp. Here I’m going to show you about the how to update any record without updating the timestamp in laravel application. From here you will learn about update without update timestamp in laravel application. We can see laravel update query without update…
View On WordPress
0 notes
codesolutionsstuff · 3 years ago
Text
Laravel 9 GEO Chart Example using LavaCharts
Tumblr media
We will teach you about Laravel - GEO Chart Example using lavacharts in this article. Here, we'll explain in detail how to use Laravel's GEO Chart Example utilizing lavacharts and provide you with a sample if that's what you need. Today, I'm going to demonstrate how to use the lavacharts package to add a geochart to your Laravel 5 application. Typically, we used geochart on the back end to visually check users according to their country. In this article, we'll use a geo-chart that shows the number of users by country. The benefit of lavachart is that you can manage all data with chart metadata from the controller, rendering just on view. Other charts, such as bar charts, area charts, column charts, pie charts, and line charts, are also available at lavacharts. We'll utilize a geo chart with excellent graphics in this post. You just need to follow a few steps and you can use it in your Laravel application to receive the output seen in the preview below.
Step 1: Installation
Downloading the Lavacharts package in order to create a chart file from a view blade file is the first step. Run the following command in your terminal first, then: composer require khill/lavacharts Open the config/app.php file right now and add the service provider. 'providers' =>
Step 2: Add Table and Model
We need to make a new table called "country users" so that we can get data from it; you can make your own table instead, but this is just an example. Using the Laravel 5 php artisan command, we need to build a migration for the country users table. To start, run the following line: php artisan make:migration create_country_users_table Following this command, you will find a file in the database/migrations directory. You must add the following code to your migration file in order to build the country users table. use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; class CreateCountryUsersTable extends Migration { public function up() { Schema::create('country_users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('total_users'); $table->timestamps(); }); } public function down() { Schema::drop("country_users"); } } Create the CountryUser model for country users after creating the "country users" table by creating the following file in the app/CountryUser.php directory: app/CountryUser.php namespace App; use IlluminateDatabaseEloquentModel; class CountryUser extends Model Okay, you may now add a few records as seen below: See also: How to use Highcharts to add charts in Laravel.{ public $fillable = ; } Okay, you may now add a few records as seen below: See also: How to use Highcharts to add charts in Laravel.
Step 3: Add Route
We must include the route in this stage in order to generate the view. so add the following route by opening your app/Http/routes.php file. Route::get('laracharts', 'ChartController@getLaraChart');
Step 4: Create Controller
In this directory, app/Http/Controllers/ChartController.php, we should now construct a new controller named ChartController. Ensure that the country users table contains some data. The following information should be included in the controller file because it will manage data, chart data, and view files: app/Http/Controllers/ChartController.php namespace AppHttpControllers; use IlluminateHttpRequest; use KhillLavachartsLavacharts; use AppCountryUser; class ChartController extends Controller { public function getLaraChart() { $lava = new Lavacharts; // See note below for Laravel $popularity = $lava->DataTable(); $data = CountryUser::select("name as 0","total_users as 1")->get()->toArray(); $popularity->addStringColumn('Country') ->addNumberColumn('Popularity') ->addRows($data); $lava->GeoChart('Popularity', $popularity); return view('laracharts',compact('lava')); } }
Step 4: Create View File
The final step is to build the view file "laracharts.blade.php" in order to generate the view chart. To do this, create the file and add the following code: resources/view/laracharts.blade.php You may now go and check. Here is a link where you may learn more about laracharts: laracharts. I'm hoping this code and text will help you use Laravel 9 GEO Chart Example using LavaCharts Example. Read the full article
0 notes
sechno · 3 years ago
Text
While designing database structure, you may get to know that some tables are related to one another. For example in a blog application, a user have many posts and post have many comments. In a MySQL database tables, we add one table's id to another table or create pivot table to create relationship between tables. Laravel provides eloquent relationship which provides powerful query builders. In Laravel, eloquent relationships are defined in model classes. Laravel eloquent provides easy ways to create common relationships: one to one one to many many to many has one of many has one through has many through one to one polymorphic one to many polymorphic many to many polymorphic In this article, we will discuss on Laravel's one to one polymorphic eloquent relationship. This is similar to one-to-one relationship. However, in this relationship, one model may have associated with more than one model. For example, a Profile model may be associated with User model as well as Admin model. Example: Now, in this example, we will build relationship between Profile model with User and Admin model. We assume that you have created fresh Laravel application. We also assume that you have confiured database connection. Database tables In this relationship, we have three database tables: users, admins and profiles. A profiles table will be related with users and admins table. Migration we need three migration table. We already have users migration. Run the following commands into Terminal to create remaining migration classes at database/migrations directory. php artisan make:migration create_admins_table php artisan make:migration create_profiles_table Below are the migration table fields for these table: users migration In the users migration, we have defined the following fields: /** &nbsp;* Run the migrations. &nbsp;* &nbsp;* @return void &nbsp;*/ public function up() &nbsp; &nbsp; Schema::create('users', function (Blueprint $table) &nbsp; &nbsp; &nbsp; &nbsp; $table->id(); &nbsp; &nbsp; &nbsp; &nbsp; $table->string('name'); &nbsp; &nbsp; &nbsp; &nbsp; $table->string('email')->unique(); &nbsp; &nbsp; &nbsp; &nbsp; $table->string('password'); &nbsp; &nbsp; &nbsp; &nbsp; $table->timestamps(); &nbsp; &nbsp; ); admins migration /** &nbsp;* Run the migrations. &nbsp;* &nbsp;* @return void &nbsp;*/ public function up() &nbsp; &nbsp; Schema::create('admins', function (Blueprint $table) &nbsp; &nbsp; &nbsp; &nbsp; $table->id(); &nbsp; &nbsp; &nbsp; &nbsp; $table->string('name'); &nbsp; &nbsp; &nbsp; &nbsp; $table->string('email')->unique(); &nbsp; &nbsp; &nbsp; &nbsp; $table->string('password'); &nbsp; &nbsp; &nbsp; &nbsp; $table->timestamps(); &nbsp; &nbsp; ); profiles migration /** &nbsp;* Run the migrations. &nbsp;* &nbsp;* @return void &nbsp;*/ public function up() &nbsp; &nbsp; Schema::create('profiles', function (Blueprint $table) &nbsp; &nbsp; &nbsp; &nbsp; $table->id(); &nbsp; &nbsp; &nbsp; &nbsp; $table->string('image_url'); &nbsp; &nbsp; &nbsp; &nbsp; $table->string('github'); &nbsp; &nbsp; &nbsp; &nbsp; $table->integer('profileable_id'); &nbsp; &nbsp; &nbsp; &nbsp; $table->string('profileable_type'); &nbsp; &nbsp; &nbsp; &nbsp; $table->timestamps(); &nbsp; &nbsp; ); Now, let's look at the migration fields. We have profileable_id and profileable_type fields in the profiles migration. The profileable_id will store id value of user or admin and profileable_type will store the User or Admin class name like AppModelsUser or AppModelsAdmin. Now run the migrate command to create tables into database. php artisan migrate Model Laravel models are located at app/Models directory. We already have User model. Create the rest of model classes for these tables using following Artisan commands one by one into Terminal. php artisan make:model Admin php artisan make:model Profile Now let's build relationship. First create profileable() method into Profile model which will return morphTo() method. This will retrieve the parent model record.
0 notes
jvlcode · 3 years ago
Video
youtube
Laravel 8 in Tamil - How to use Timestamps?
0 notes
otfcoder · 4 years ago
Text
Tumblr media
#Laravel Tip for the Day...
Default TimeStamp
Follow us on Facebook, Instagram, LinkedIn, Pinterest, Tumblr, And Twitter...for more Tips and Updates. . . . . #timestamp #defaulttimestamp #laraveldevelopers #laraveltips #laravelphp #php #programming #programmer #developer #tips #webdevelopmentcompany #coding #codingtips #otfcoder #otfcodermarketingservices #laraveldeveloper
0 notes
decodewebin · 6 years ago
Text
How to create a guard in laravel ?
As I said earlier, make another table and model for admin users, admin table and Admin model respectively using following commands.
php artisan make:migration create_admins_table
And for Admin model
php artisan make:model Models/Admin
You can copy the database schema of users table to admins table from database/migrations/<timestamp>_create_users_table.php or you can add your custom schema too.
Edit config/auth.php
Add following in guards array:
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
And in providers array:
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
2 notes · View notes