#laravel connect db
Explore tagged Tumblr posts
Text
There is no deficit of PHP frameworks nowadays for a web development company to choose from. They come in all shapes and sizes for developers with different hosting capabilities, skills, application needs, and development time-frames. The common goal of all PHP frameworks is to make the development process faster and easier. PHP frameworks help to simplify complex coding problems by providing developers with a platform for developing powerful web applications in a short time. The PHP structure allows for rapid application development (RAD), which saves a lot of time and reduces the need to run coding from scratch, ensuring stable application development. Without the help of a PHP infrastructure, developing mobile and web applications can challenging for beginners when it comes to writing code and creating a connection between a database and an application that is being developed from scratch. The use of the PHP Framework reduces the workload. The best thing about PHP frameworks is the ease of adaptation, as well as the ability to learn them faster compared to other programming languages. Although, every developer that has ever worked with a framework before, knows that each of them is unique and should be chosen depending on the anticipated result. Below we will review the best frameworks out there in 2019 to provide everything you need to know to choose the best one for you. Choosing a PHP Framework Before making a choice in favor of one particular framework, you should consider its following characteristics: Functionalities and components; Development frequency; Learning curve; Community size. You want to choose a framework that is easy to learn and provides fast development with good looking frontends. Let’s see which ones out of our Top 5 list suit these requirements the best, defining strengths and weaknesses of each of them. Laravel If you start searching for a PHP framework, this one will most likely come up first. Laravel owes its wide popularity to its easiness of use and wide range of inbuilt features. Strengths Developer-friendliness (easy to learn); Innovative technology (relatively new tool); High speed of development; High security (strong encryption packages); Convenient files and code organization; Great documentation; MVC architecture (and PHP7); Unit testing (FAST on HHVM); Advanced out of the box functionality; Routing (the easiest to manage); ORM support; Large community. Weaknesses Higher bugs possibility; Not easy to transfer legacy systems; Does lots of queries on the DB; Does not work on shared hosting plans. Symfony This tool will provide you with a rich variety of features. Symfony has earned a reputation of a reliable and mature PHP framework through the years. Strengths High performance; Flexibility; Reliability; Great documentation, maintenance, and support; Large community. Weaknesses Not an easy learning process; Reduced speed of development; No MVC support. Phalcon This tool is different in its coding style. Phalcon coding is based on C and C++, not holding it from providing an advanced set of development features you can use. Strengths Easy to learn; Very high speed of development; Autoloading; Advanced security features; Traditional MVC code; Great documentation. Weaknesses Not as open source as Laravel; Does not work on shared hosting plans; Does not work with HHVM. Yii 2 It is one of the oldest PHP frameworks that provide support and efficiently to answer modern development needs. You can call Yii 2 a more developer-friendly competitor of Symfony 2 with its easy learning curve. Strengths Easy to learn; Flexibility; High security; High speed of development; Variety of configuration; MVC and object-oriented; Availability to build small CRUD applications immediately. Weaknesses The lack of built-in allowances; No AR queries; Too many libraries & dependencies; Doesn’t allow multiple relations built up.
CodeIgniter If you need a powerful tool with advanced features, this one might be for you. CodeIgniter is appreciated among developers for allowing them to focus on creativity. Strengths Developer friendliness; Standard databases use (such as MySQL); Easy to extend and customize; Supports Web Page and Database Caching; Good documentation and support; Requires little coding; Built-in security feature Weaknesses Does no support code modular separation by default; Lacks exhaustive libraries that are built inside the framework. Summary There are many programming languages you can use, but PHP is still the best option for server-side scripting. However, even if you are a PHP professional, coding all parts of each new project will take a long time. However, if you choose the best PHP framework for your needs, you can skip a lot of the basics and go straight to the interesting part of developing a new project. Although we have shortlisted top 5 PHP frameworks of 2019, you will have your own opinion on each of them, depending on the goals you have set for your project. Above are the main factors that might influence your choice. Consider them and decide which one is a match with your requirements.
0 notes
Text
Best way to Check Table Existence in the Database Laravel?
in this tutorial learn how to checking table exists in database or not, I have guide step by step how to check table exists in your database. In Laravel, there are multiple ways to check if a database table exists. I’ll provide you with a few different methods you can use: Total method 1.Schema Builder’s hasTable method: 2.Using the DB facade: 3.Using the connection…
View On WordPress
0 notes
Photo
Deploy laravel project with docker swarm We check three major step in this guide Setup laravel project with docker compose Deploy the stack to the swarm Create gitlab-ci Setup laravel project with docker compose we will explore the process of deploying a laravel project using docker swarm and setting up a CI/CD pipline to automate the deployment process. Now let’s start with containerize a laravel project with docker compose we need three separate service containers: An app service running PHP7.4-FPM; A db service running MySQL 5.7; An nginx service that uses the app service to parse PHP code Step 1. Set a env variable in project In root directory of project we have .env file now we need to update some variable DB_CONNECTION=mysql DB_HOST=db DB_PORT=3306 DB_DATABASE=experience DB_USERNAME=experience_user DB_PASSWORD=your-password Step 2. Setting up the application’s Docekrfile we need to build a custom image for the application container. We’ll create a new Dockerfile for that. Docker file FROM php:7.4-fpm # Install system dependencies RUN apt-get update && apt-get install -y \ git \ curl \ libpng-dev \ libonig-dev \ libxml2-dev \ zip \ unzip # Clear cache RUN apt-get clean && rm -rf /var/lib/apt/lists/* # Install PHP extensions RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd # Get latest Composer COPY --from=composer:latest /usr/bin/composer /usr/bin/composer # Set working directory WORKDIR /var/www Step 3. Setting up Nginx config and Database dump file In root directory create a new directory called docker-compose Now we need two other directories, a nginx directory and mysql directory So we have this two route in our project laravel-project/docker-compose/nginx/ laravel-project/docker-compose/mysql/ In nginx directory create a file called experience.conf we write nginx config in this file like: server { listen 80; index index.php index.html; error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; root /var/www/public; location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass app:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; } location / { try_files $uri $uri/ /index.php?$query_string; gzip_static on; } } In mysql directory create a file called init_db.init we write mysql initialization in this file like: DROP TABLE IF EXISTS `places`; CREATE TABLE `places` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `visited` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; INSERT INTO `places` (name, visited) VALUES ('Berlin',0),('Budapest',0),('Cincinnati',1),('Denver',0),('Helsinki',0),('Lisbon',0),('Moscow',1); Step 4. Creating a multi container with docker-compose We need a building three container that should share networks and data volumes. Ok so create a docker-compose file in root directory of project For craete a network for connecting services we define network in docker-compose file like this: networks: experience: driver: bridge App service: app: build: context: ./ dockerfile: Dockerfile image: travellist container_name: experience-app restart: unless-stopped working_dir: /var/www/ volumes: - ./:/var/www networks: - experience DB service: db: image: mysql:8.0 container_name: experience-db restart: unless-stopped environment: MYSQL_DATABASE: ${DB_DATABASE} MYSQL_ROOT_PASSWORD: ${DB_PASSWORD} MYSQL_PASSWORD: ${DB_PASSWORD} MYSQL_USER: ${DB_USERNAME} SERVICE_TAGS: dev SERVICE_NAME: mysql volumes: - ./docker-compose/mysql:/docker-entrypoint-initdb.d networks: - experience Nginx service: nginx: image: nginx:1.17-alpine container_name: experience-nginx restart: unless-stopped ports: - 8000:80 volumes: - ./:/var/www - ./docker-compose/nginx:/etc/nginx/conf.d networks: - experience So our docker-compose file be like this: version: "3.7" services: app: build: context: ./ dockerfile: Dockerfile image: travellist container_name: experience-app restart: unless-stopped working_dir: /var/www/ volumes: - ./:/var/www networks: - experience db: image: mysql:8.0 container_name: experience-db restart: unless-stopped environment: MYSQL_DATABASE: ${DB_DATABASE} MYSQL_ROOT_PASSWORD: ${DB_PASSWORD} MYSQL_PASSWORD: ${DB_PASSWORD} MYSQL_USER: ${DB_USERNAME} SERVICE_TAGS: dev SERVICE_NAME: mysql volumes: - ./docker-compose/mysql:/docker-entrypoint-initdb.d networks: - experience nginx: image: nginx:alpine container_name: experience-nginx restart: unless-stopped ports: - 8100:80 volumes: - ./:/var/www - ./docker-compose/nginx:/etc/nginx/conf.d/ networks: - experience networks: experience: driver: bridge Step 5. Running application with docker compose Now we can build the app image with this command: $ docker-compose build app When the build is finished, we can run the environment in background mode with: $ docker-compose up -d Output: Creating exprience-db ... done Creating exprience-app ... done Creating exprience-nginx ... done to show information about the state of your active services, run: $ docker-compose ps Well in these 5 simple steps, we have successfully ran our application. Now we have a docker-compose file for our application that needs for using in docker swarm. Let’s start Initialize docker swarm. After installing docker in your server *attention: To install Docker, be sure to use the official documentation install docker check docker information with this command: $ docker info You should see “swarm : inactive” in output For activate swarm in docker use this command: $ docker swarm init The docker engine targeted by this command becomes a manager in the newly created single-node swarm. What we want to use is the services of this docker swarm. We want to update our service like app with docker swarm, The advantage of updating our service in Docker Swarm is that there is no need to down the app service first, update the service, and then bring the service up. In this method, with one command, we can give the image related to the service to Docker and give the update command. Docker raises the new service without down the old service and slowly transfers the load from the old service to the new service. When running Docker Engine in swarm mode, we can use docker stack deploy to deploy a complete application stack to the swarm. The deploy command accepts a stack description in the form of a Compose file. So we down our docker compose with this command: $ docker-compose down And create our stack. ok if everything is ok until now take a rest Deploy the stack to the swarm $ docker stack deploy --compose-file docker-compose.yml For example : $ docker stack deploy --compose-file docker-compose.yml staging Probably you see this in output: Creating network staging_exprience Creating service staging_nginx failed to create service staging_nginx: Error response from daemon: The network staging_exprience cannot be used with services. Only networks scoped to the swarm can be used, such as those created with the overlay driver. This is because of “driver: bridge” for deploying your service in swarm mode you must use overlay driver for network if you remove this line in your docker compose file When the stack is being deployed this network will be create on overlay driver automatically. So our docker-compose file in network section be like this: networks: experience: And run upper command: $ docker stack deploy --compose-file docker-compose.yml staging For now you probably you see this error : failed to create service staging_nginx: Error response from daemon: The network staging_experience cannot be used with services. Only networks scoped to the swarm can be used, such as those created with the overlay driver. Get network list in your docker: $ docker network ls Output: NETWORK ID NAME DRIVER SCOPE 30f94ae1c94d staging_experience bridge local So your network has local scope yet because in first time deploy stack this network save in local scope and we must remove that by: $ docker network rm staging_experience After all this run command: $ docker stack deploy --compose-file docker-compose.yml staging Output: Creating network staging_experience Creating service staging_app Creating service staging_db Creating service staging_nginx Now get check stack by: $ docker stack ls Output: NAME SERVICES staging 3 And get service list by: $ docker service ls Output: If your REPLICAS is 0/1 something wrong is your service For checking service status run this command: $ docker service ps staging_app for example And for check detail of service run this command: $ docker service logs staging_app for example Output of this command show you what is problem of your service. And for updating your a service with an image the command you need is this: $ docker service update --image "<your-image>" "<name-of-your-service>" --force That's it your docker swarm is ready for zero down time deployment :))) Last step for have a complete process zero down time deployment is create pipeline in gitlab. Create gitlab-ci In this step we want create a pipeline in gitlab for build, test and deploy a project So we have three stage: stages: - Build - Test - Deploy Ok let’s clear what we need and what is going on in this step . We want update laravel project and push our change in gitlab create a new image of this changes and test that and after that log in to host server pull that updated image in server, and update service of project. For login to server we need define some variable in gitlab in your repository goto setting->CI/CD->VARIABLES Add variable Add this variables: CI_REGISTRY : https://registry.gitlab.com DOCKER_AUTH_CONFIG: { "auths": { "registry.gitlab.com": { "auth": "<auth-key>" } } } auth-key is base64 hash of “gitlab-username:gitlab-password” SSH_KNOWN_HOSTS: Like 192.168.1.1 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCGUCqCK3hNl+4TIbh3+Af3np+v91AyW4+BxXRtHBC2Y/uPJXF2jdR6IHlSS/0RFR3hOY+8+5a/r8O1O9qTPgxG8BSIm9omb8YxF2c4Sz/USPDK3ld2oQxbBg5qdhRN28EvRbtN66W3vgYIRlYlpNyJA+b3HQ/uJ+t3UxP1VjAsKbrBRFBth845RskSr1V7IirMiOh7oKGdEfXwlOENxOI7cDytxVR7h3/bVdJdxmjFqagrJqBuYm30 You can see how generate ssh key in this post: generate sshkey SSH_PRIVATE_KEY: SSH_REMOTE_HOST: root@ This is your variables in gitlab. So let’s back to gitlab-ci In root directory of project create a new file .gitlab-ci.yml and set build stage set test stage And in the last set deploy stage like: stages: - Build - Test - Deploy variables: IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-$CI_COMMIT_SHORT_SHA build: stage: Build image: docker:20.10.16 services: - docker:dind script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY - docker build --pull -f Dockerfile -t $IMAGE_TAG . - docker push $IMAGE_TAG preparation: stage: Test image: $IMAGE_TAG needs: - build script: - composer install artifacts: expire_in: 1 day paths: - ./vendor cache: key: ${CI_COMMIT_REF_SLUG}-composer paths: - ./vendor unit-test: stage: Test image: $IMAGE_TAG services: - name: mysql:8 alias: mysql-test needs: - preparation variables: APP_KEY: ${APP_KEY} MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_DATABASE: ${MYSQL_DATABASE} DB_HOST: ${DB_HOST} DB_USERNAME: ${DB_USERNAME} DB_PASSWORD: ${DB_PASSWORD} script: - php vendor/bin/phpunit staging-deploy: stage: Deploy extends: - .deploy-script variables: APP: "stackdemo_app" STACK: "travellist-staging" only: - develop needs: - unit-test environment: name: stage .remote-docker: variables: DOCKER_HOST: ssh://${SSH_REMOTE_HOST} image: docker:20.10.16 before_script: - eval $(ssh-agent -s) - echo $IMAGE_TAG - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - - mkdir -p ~/.ssh - chmod 700 ~/.ssh - echo "HOST *" > ~/.ssh/config - echo "StrictHostKeyChecking no" >> ~/.ssh/config - echo -n $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER --password-stdin $CI_REGISTRY .deploy-script: extends: - .remote-docker script: - cp $develop_config /root/project/core - docker pull $IMAGE_TAG - docker service update --image "$IMAGE_TAG" "$APP" --force dependencies: [] Change something in your project and push to gitlab and wait for it To see all pipeline pass like this : And this is beautiful. https://dev.to/holyfalcon/deploy-laravel-project-with-docker-swarm-5oi
0 notes
Text
Use Laravel’s Illuminate Database Query Builder With WordPress
I’ve been working on Smolblog, a social web blogging app. To help me get to a minimally viable product sooner, I’ve been building it on top of WordPress. However, WordPress is built exclusively for the MySQL database, and I eventually want Smolblog to work with many different databases, especially SQLite. This means, for my own code, I need to abstract the database away.
The first pass I had at this was to simply have Query objects and services to handle those. This would effectively abstract away the entire data layer, making it completely system-agnostic. It wouldn’t even need to be a traditional database. But as I built this system out, I was making more and more assumptions about what the database and data code would look like. And while the database code was all abstracted away, I still had to write it. A lot of it. And every line I wrote using $wpdb was another line I’d have to rewrite someday.
I’ve been looking at other frameworks to use, and Laravel is by far the strongest contender. Their approach to dependency injection and services seems to line up well with how I’ve organically built Smolblog to this point. So when I found out that their database abstraction layer also included a way to use the library without taking on the entire Laravel framework, I decided to make “someday” today.
Prerequisites
Composer: While you can use this library without using Composer, it’s very much not recommended. That being said, if you’re using this in a plugin for general use or otherwise don’t have control over your entire WordPress environment, be sure to use Mozart or some other tool to isolate the namespaces of your dependencies.
Populated database constants: Some of the more modern WordPress setups use a connection string or other way to connect to MySQL. I didn’t find a way to get that information out of the $wpdb constant, so this code relies on having DB_HOST and other constants from wp-config.php defined.
PDO::MySQL: Illuminate DB uses PDO to handle databases, so you’ll need to make sure your PHP server has the PDO::MySQL extension installed. I’m using the official PHP image, so I needed to add these two lines to my Dockerfile:
RUN docker-php-ext-install pdo_mysql RUN docker-php-ext-enable pdo_mysql
Step 1: Dependency Injection
We’re going to use dependency injection to separate creating the database connection from using the database connection. This way the database connection can change without as much code changing.
The documentation for Laravel’s query builder involves calling their DB facade, a global class that calls a singleton instance. Digging through the documentation and code, it looks like the underlying class conforms to the Illuminate\Database\ConnectionInterface interface. So that’s what we’ll use in our service’s constructor:
use Illuminate\Database\ConnectionInterface; class ContentEventStream implements Listener { public function __construct( private ConnectionInterface $db, ) { } }
Inside the service, we’ll follow the documentation, replacing any use of the DB facade with our $db object:
$this->db->table('content_events')->insert(['column' => 'value']);
Step 2: Connection Factory
Now that we know what we need, we need to create it.
The README for the Illuminate Database package has good starting instructions. We’ll combine those with data from wp-config.php and $wpdb:
use Illuminate\Database\Capsule\Manager; use Illuminate\Database\ConnectionInterface; function getLaravelConnection(): ConnectionInterface { global $wpdb; $capsule = new Manager(); $capsule->addConnection( [ 'driver' => 'mysql', 'host' => DB_HOST, 'database' => DB_NAME, 'username' => DB_USER, 'password' => DB_PASSWORD, 'charset' => DB_CHARSET, 'prefix' => $wpdb->prefix, ] ); return $capsule->getConnection(); }
(As mentioned, we’re pulling the connection information straight from configuration. If you know how to get it from $wpdb, let me know!)
The prefix property on the connection works much the same way as WordPress' table prefix. Since we’re using the connection object to also build our queries, it will add the prefix to our queries automatically. Using this property will also use the correct tables for blogs in multisite, so data from one blog doesn’t leak into another.
For Smolblog, I only want one set of tables regardless of multisite. I also want to prefix the Smolblog-specific tables, mostly so they’re all in one place when I’m scrolling. So my prefix property looks like this:
$capsule->addConnection( [ // ... 'prefix' => $wpdb->base_prefix . 'sb_', ] );
Because I don’t want a global object or the Eloquent ORM, I can ignore the rest of the setup from the project README.
Finally, we’ll want to store this created object somewhere central. Smolblog uses a simple dependency injection container, so we’ll store it there. The first time a service that needs a database connection is created, the container will run this function and provide the object.
(Honestly, the container probably deserves a blog post of its own; you can look at the source code in the meantime.)
Step 3: Update the Schema
We have our code to build queries. We have our connection to the database. The only thing we need now is the actual tables for the database.
Here is where we can use WordPress to its full extent. We will be using the dbDelta function in particular. This will tie into WordPress' existing system for updating the database structure alongside WordPress itself.
Some plugins tie this migration code to an activation hook, but we want to be able to modify the tables even after the plugin is activated. So our process will look like this:
Loop through the different tables we will need.
Check the blog options for a schema version.
If the version matches what we have in code, we’re up-to-date. Skip to the next table.
Pass the new table schema to dbDelta and let it do its thing.
Save the schema version to blog options.
Rinse and repeat for each table.
At this point, I should bring up some of the caveats with the dbDelta function. The comments on the WordPress documentation are invaluable here, especially as they point out a few things that need to be consistent with our schemas.
Because there’s so many things that need to be consistent, we’ll isolate the unique parts of our table schemas to two things:
A name. Because every table needs one. We will declare it without the prefix.
The fields excluding the primary key. We can have UNIQUE indexes on other fields for a similar effect, but every table will have an auto-incrementing id field.
A series of values keyed to short strings? That sounds like an array! Here’s part of what Smolblog’s schema array looks like:
class DatabaseHelper { public const SCHEMA = [ 'content_events' => <<<EOF event_uuid varchar(40) NOT NULL UNIQUE, event_time varchar(30) NOT NULL, content_uuid varchar(40) NOT NULL, site_uuid varchar(40) NOT NULL, user_uuid varchar(40) NOT NULL, event_type varchar(255) NOT NULL, payload text, EOF, 'notes' => <<<EOF content_uuid varchar(40) NOT NULL UNIQUE, markdown text NOT NULL, html text, EOF, ]; public static function update_schema(): void { foreach ( self::SCHEMA as $table => $fields ) { self::table_delta( $table, $fields ); } } //... }
A brief aside: Smolblog uses UUIDs for its unique identifiers, and they’re stored here as full strings in fields ending with _uuid. I ran into trouble storing them as bytes, and something in WordPress would frequently mess with my queries when I had fields named things like user_id and site_id. I’m noting this here in case you run into the same things I did.
When WordPress loads the plugin, it will call the update_schema function declared here. That function loops through the array, extracts the table name and fields, and passes them to this function:
public static function table_delta( string $table, string $fields ): void { global $wpdb; $table_name = $wpdb->base_prefix . 'sb_' . $table; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id bigint(20) NOT NULL AUTO_INCREMENT, $fields PRIMARY KEY (id) ) $charset_collate;"; if ( md5( $sql ) === get_option( $table . '_schemaver', '' ) ) { return; } require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql ); update_option( $table . '_schemaver', md5( $sql ) ); }
This function takes care of the boilerplate we talked about earlier and runs the steps:
It creates the table name using the same pattern as before: the base prefix plus sb_.
It creates a CREATE TABLE SQL statement using the table name and fields. (It’s okay to build a SQL query this way because all of the data is coming from constants inside the PHP file; none of it is coming from form data or other untrusted sources.)
It takes the MD5 hash of the SQL statement and compares that to the saved option for this table. The hash will change when the code changes, so this is a quick way to keep our code and database in-sync.
If the database needs to be updated, it requires the correct file from WordPress Core and runs the dbDelta function.
Finally, it saves the MD5 hash to the blog options so we know what version the database is on.
By calculating the version using the hash of the actual SQL, we don’t have to worry about whether some other version number has been updated. This may or may not be the approach you want to take in a production application, but it has proven very useful in development. This is the same idea as using the filemtime function as the “version number” of static CSS and JavaScript in your theme.
So there we have it. We’ve used the connection information in WordPress to hook up a Laravel database connection. And at some point in the future, it’ll be that much easier to let Smolblog work with SQLite which will in turn let Smolblog work on even more web hosts. And you can use this to do whatever you want! Maybe you just wanted to transfer some skills from Laravel to WordPress. Maybe you’re just in it for the academic challenge.
One thing you can do with this is unit-test your services using an in-memory SQLite database��� and I’ll leave you with that.
final class DatabaseServiceUnitTest extends \PHPUnit\Framework\TestCase { private \Illuminate\Database\Connection $db; private DatabaseService $subject; protected function setUp(): void { $manager = new \Illuminate\Database\Capsule\Manager(); $manager->addConnection([ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); $manager->getConnection()->getSchemaBuilder()->create( 'content_events', function(\Illuminate\Database\Schema\Blueprint $table) { $table->uuid('event_uuid')->primary(); $table->dateTimeTz('event_time'); $table->text('payload'); } ); $this->db = $manager->getConnection(); $this->subject = new DatabaseService(db: $this->db); } public function testItPersistsAContentEvent() { $event = new class() extends ContentEvent { public function __construct() { parent::__construct( id: Identifier::fromString('8289a96d-e8c7-4c6a-8d6e-143436c59ec2'), timestamp: new \DateTimeImmutable('2022-02-22 02:02:02+00:00'), ); } public function getPayload(): array { return ['one' => 'two', 'three' => 'four']; } }; $this->subject->onContentEvent($event); $expected = [ 'event_uuid' => '8289a96d-e8c7-4c6a-8d6e-143436c59ec2', 'event_time' => '2022-02-22T02:02:02.000+00:00', 'payload' => '{"one":"two","three":"four"}', ]; $this->assertEquals((object)$expected, $table->first()); $this->assertEquals(1, $table->count()); } }
1 note
·
View note
Text
[Laravel][Testing] Display clearly the not found in the database error message
Problem
When seeInDatabase asserting was failed, I can’t not known where the path of properies is not match.
Example: With bellow test, I will receive the bellow message.
Test code:
$this->seeInDatabase('les_knowledge', [ 'lesson_id' => $lesson->id, 'number' => 1, 'content_en' => '~ years old DIFFFFFFFFFF', 'explanation_en' => 'In Japan, you are born as a 0 year-old and turn 1 on your first birthday.', ]);
Test result:
Unable to find row in database table [les_knowledge] that matched attributes
[{ "lesson_id":98,"number":1, "content_en":"~ years old DIFFFFFFFFFF", "explanation_en":"In Japan, you are born as a 0 year-old and turn 1 on your first birthday." }]
It is hard to find where is the path don’t match.
Solution
Create a function likes a bellow.
function seeInDatabaseAndHasProperties($table, array $filter, array $properties, $connection = null){ $this->seeInDatabase($table, $filter, $connection); $model = (array)DB::table($table)->where($filter)->first(); $this->assertEquals($properties, Arr::only($model, array_keys($properties))); }
Test code will be:
$this->seeInDatabaseAndHasProperties('les_knowledge', [ 'lesson_id' => $lesson->id, 'number' => 1, ], [ 'content_en' => '~ years old DIFFFFFFFFFF', 'explanation_en' => 'In Japan, you are born as a 0 year-old and turn 1 on your first birthday.', ]);
Test result will be:
Failed asserting that two arrays are equal. --- Expected +++ Actual @@ @@ Array ( - 'content_en' => '~ years old DIFFFFFFFFFF' + 'content_en' => '~ years old' 'explanation_en' => 'In Japan, you are born as a 0...thday.' )
Now you can easily see which properties don’t match.
1 note
·
View note
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
Text
Laravel 6 Beginner - e7 - MySQL Database & SQLite
Laravel 6 Beginner – e7 – MySQL Database & SQLite
[ad_1] Let’s get the basics of working with a database in Laravel by setting up a MySQL database from scratch. Let’s also create a migration and a model for our services. To wrap it up, let’s change to a SQLite database to show how simple it is.
For the best experience, follow along in our interactive school at https://www.coderstape.com
DigitalOcean Referral https://m.do.co/c/7dce5364ef4d
About…
View On WordPress
#awesome laravel projects#database#database configuration laravel#database migrations laravel#eloquent#Laravel#laravel 6#laravel 6 database#laravel 6 mysql#laravel connect db#laravel database#laravel database configuration#laravel database settings#laravel db settings#laravel for beginners#laravel from scratch#laravel from the ground up#laravel migration#laravel model explained#laravel mvc#laravel mysql#laravel sqlite#php mysql laravel
0 notes
Text
有 Lazy Connection 功能的 PDO object
有 Lazy Connection 功能的 PDO object
在「Aura.Sql」這邊看到有提供 Lazy Connection 的 PDO object,而且是繼承自本來的 PDO object: Provides an extension to the native PDO along with a profiler and connection locator. Because ExtendedPdo is an extension of the native PDO, code already using the native PDO or typehinted to the native PDO can use ExtendedPdo without any changes. Lazy connection. ExtendedPdo connects to the database only on method calls that…
View On WordPress
0 notes
Text
How To Use Chart JS In Laravel
The fundamentals of Chart.js are quite straightforward. First, we must install Chart.js into our project. Depending on the settings of your project, you may be installing it using npm or bower, or you may link to a constructed version via a CDN or clone/build from GitHub. Simply connecting to the created CDN version in the sample's blade file would suffice for this brief example. A The fundamentals of Chart js are quite straightforward. First, we must install Chart js into our project. Depending on the settings of your project, you may be installing it using npm or bower, or you may link to a constructed version via a CDN or clone/build from GitHub. In our examples, we'll only link to the built-in CDN version for the purposes of this brief demonstration. We'll just plot the ages of the app users in this case. We're presuming you've already set up the Laravel auth scaffolding and carried out the required migrations to make a Users table. If not, take a look at the information here or modify it for the model you're using for your chart's data. Therefore, before creating any users at random, we'll first add an age column to our Users table. For more information, see our post on how to use faker to create random users, however for this demonstration, let's make a database migration to add an age column by using: add age to users table php artisan make:migration —table='users' To change the up function to: edit this file in the database migrations directory. Schema::table('Users', function (Blueprint $table) { $table->int('age')->nullable(); }); Run php artisan migrate after that, and your Users table should now contain an age column. Visit /database/factories/UserFactory now, and add the following at the end of the array: 'age' is represented by $faker->numberBetween($min = 20, $max = 80), The complete return is thus: return ; Run the following commands to build a UsersTableSeeder: make:seeder UsersTableSeeder in PHP This will produce UsersTableSeeder.php in the database. The run function should include the following: factory(AppUser::class, 5)->create(); When this is executed, 5 users will be created; modify 5 to the number of users you need. After that, we must open DatabaseSeeder.php in /database/seeds and uncomment the code in the run() function. Finally, execute php artisan db:seed. Five new users should appear, each of whom has an age. For our Charts page, we will now develop a model, controller, views, and routes. Run the following command in PHP: make:controller ChartController —model=Chart. To the file /app/Http/Controllers/ChartController.php, add the following: use AppUser; use AppChart; use DB; ... public function index() { // Get users grouped by age $groups = DB::table('users') ->select('age', DB::raw('count(*) as total')) ->groupBy('age') ->pluck('total', 'age')->all(); // Generate random colours for the groups for ($i=0; $ilabels = (array_keys($groups)); $chart->dataset = (array_values($groups)); $chart->colours = $colours; return view('charts.index', compact('chart')); } The random colour scheme is one example of the exciting things you can do with the controller's data, though you can also specify hardcoded colours if you'd choose. In /resources/views/charts/, we must now create an index.blade.php file and add the following (depending on your blade setup and layout; here is an example): Laravel Chart Example Chart Demo Finally, we need to add the following to /routes/web.php: Route::get('/charts', 'ChartController@index')->name('charts'); Go to at your-project-name.test/charts now. Although this should serve as a good starting point for your understanding of the fundamentals of charts and graphs in Laravel, you may refer to the Chart.js documentation for more details on customizing your charts. Read the full article
0 notes
Text
Aug 25
Finish setting up ui-components.
Okay, error installing.
Fixed with compatible node -V 13 to node sass
Thread-locker issues?
https://github.com/JeffreyWay/laravel-mix/issues/2383#issuecomment-643265068
mkdir -p ~/repos/web/athena/node_modules/compile-ui && sudo mount -o ro --bind ~/repos/web/ui-components ~/repos/web/athena/node_modules/compile-ui
1) drop all tables in db
2) zcat falcon.schema.sql.gz | psql -d falcon -0 -X
3) zcat falcon.data.sql.gz | psql -d falcon -0 -X --disable-triggers
AssertionError: database connection isn't set to UTC
https://stackoverflow.com/a/68025007
pip install psycopg2==2.8.6
WTF IS THIS SHIT!!???
0 notes
Text
Xampp Mysql Phpmyadmin
How to Create table in MySQL db using phpmyadmin xampp server. Start xampp control panel and run Apache, MySQL server. Open your web browser and type localhost/phpmyadmin into your address bar. Now first you have to create MySQL database so read my tutorial for How to create MySQL database in phpmyadmin. I've since uninstalled WAMP and tried XAMPP, and the problem still exists. Even just browsing the databases with PHPMyAdmin takes a long time between page loads. I am guessing it's a problem with MySQL. Any suggestions would be helpful.
Intro
Heroku offers a generous free tier for hosting up to five full-stack projects. But documentation for getting a PHP with MySQL site up and running with Heroku is poor - it took me way to much Googling. Yet the process isn't difficult, so I created this blog post to help others and myself in future deployments.
I also made a video tutorial which you can follow along to.
1. Create an account on Heroku and download Heroku CLI tools
Sign up to Heroku here.
Then download the Heroku CLI tools to allow you to write Heroku commands from your command line.
2. Open up your project folder in CLI
I’m using VS code’s integrated terminal and like to store my files in /c/xampp/htdocs/project-name but you can choose whatever you prefer.
3. Login to Heroku from the terminal
We next issue the command “heroku login���, then press any key. A login page will be opened in the browser where you can login.
4. Create an initial PHP file
We will deploy this test file.
5. Create a composer.json file
Every PHP project is required to have one when deploying to Heroku.
6. Initialise a git repository, add everything then commit
git init
git add .
git commit -m 'Added index file and composer.json'
Now for the Heroku stuff!
7. Create an Heroku project
This can easily be done through the command line but I prefer to use the Heroku website.
Login to Heroku and go to your apps dashboard.
Then click “create new app”.
Choose any available app name you want, choose your region, then click create app.
8. Push the app to Heroku
Tell git the remote Heroku repository we want to push to:
heroku git:remote -a dannys-tutorial-app
Replace “dannys-tutorial-app” with your app name from the previous step.
Then deploy to Heroku! Make sure to state the correct branch, here I am using the main branch:
git push heroku main
Heroku will then provide you with the URL to your app.
And here we have it, our app has been deployed!
9. Now to add a MySQL database

During development of your app, your app wouldv’e been connected to a local database on your machine which Heroku has no access to. So we need to set up a new MySQL database within Heroku. To do this we need to add the “ClearDB” add-on to our app.
Go to your app dashboard (https://dashboard.heroku.com/apps) and select your app.
Click Resources then add the ClearDB Add-on:
Be sure to select the free option then submit the order. You will probably be prompted to add your credit card details. Unfortunately this is required in order to add add-ons such as this to your project. But as long as you select the free option, Heroku won’t charge you.
Xampp Phpmyadmin Mysql Password
10. Get your database URL
Got to “settings” then scroll down to “config vars”. Copy your database URL into a text editor or word document for later use.
Here’s mine: mysql://b0cc1049d026d1:[email protected]/heroku_3b61f10a737bcca?reconnect=true
The URL contains the information you need to connect to your new Heroku MySQL database via PHPMyAdmin:
Username: b0cc1049d026d1
Password: da2394e8
Host: eu-cdbr-west-03.cleardb.net
Xampp Mysql Setup
11. Configure PHPMyAdmin to connect to the database
We now need to tell PHPMyAdmin our Heroku database information so that it can connect to it.
You need find your config.inc.php file which stores configuration information. My PHPMyAdmin came with XAMPP and so my config file is located here:
C:xamppphpMyAdminconfig.inc.php
Open Phpmyadmin Xampp
Open up this file in any text editor, I’m using VS code but you could use something like notepad as well.
Copy the code below to the bottom of the file (but still within the PHP tags). Change the host, username and password to the one’s you obtained from the URL before.
12. Configure your Heroku MySQL database
Open up PHPMyAdmin. If using XAMPP it can be done as below:
Open up the server side-panel and select your newly added Heroku server:
Go over to databases and select your Heroku database.
You can now create the tables you need in your database.
13. Connect to the Heroku database from PHP
Copy in the code below to load in your Heroku database configuration variables to your app. This will connect your app to the database.
And that’s it! We have deployed a PHP project to Heroku, made a remote MySQL database, configured the database using PHPMyAdmin, and finally connected our app to the database.
If that was helpful, you can say thanks by subscribing to my YouTube channel. Leave a comment if you have any questions or feedback (positive or negative) :)
Error resolving of PhpMyAdmin access denied.
For most first time install, accessing http://localhost/PhpMyAdmin will directly take us to the PhpMyAdmin web interface without asking for password or anything because by default there is no password set. But when you install it second time you can face an error like this while accessing PhpMyAdmin.Due to that previous default loaclhost port number is not valid now.
What should be done! Let’s see in below with some easy steps.
1. So , you have to open XAMPP Control Panel ->Click MySql Config->Click my.ini
It will open in notepad as shown in figure.
2. You have to write this line skip-grant-tables after (mysqld).
3.Open xamp folder ->PhpMyAdmin .You will see config.inc.php file in phpMyAdmin folder, just open it with notepad++
$cfg(‘Servers’)($i)(‘host’) = ‘127.0.0.1’; This is default port number.
4. Resolve this issue by manually editing in the file “config.inc.php” located at “C:xamppphpMyAdmin”. Write “localhost:3307” within $cfg(‘Servers’)($i)(‘host’) = ‘localhost:3307′; as shown given picture.
Localhost Phpmyadmin Mysql Localhost Xampp
5. Save this changes. You can find port number as follows: Open XAMP->config->service port setting->mySql.
Now , you can access MyPhpAdmin.
Xampp Mysql Phpmyadmin Error
Thanks.
How to install WordPress on Windows using XAMPP? Part-1 - April 8, 2021
How to merge two or multiple tables to each other in the Laravel PHP Framework? (Part-1) - September 7, 2020
How to merge two or multiple tables to each other in the Laravel PHP Framework? (Part-3) - September 7, 2020
0 notes
Photo

Gain Nz Experience ( Industrial Internship ) Get to work on Live Projects! Web Development & Content Management Internship Learn the essential skills in Website Development and Content Management through our comprehensive training package which focuses on training you in the technologies that are hot in the market. We offer a 3 month #internship at UWD, After 3 months you will get chance to work with us on live projects and gain #NZ #experience. Our training programs go in-depth with the popular CMS (Content Management System) to give you a complete understanding of their ins and outs. Our instructors are capable developers who have years of experience using the tools utilized in the industry today. You will be learning from the best and applying your skills in a real job in no time. Industrial Internship start @ $12,999 • Full-time Job within 6 months or $9000 Refunded • Limit to 20 seats per intake • Option to stay on programme until employed • Preferential involvement in large project • Boost Programming & Communication Skills • Boost Soft Skills • PHP, HTML5, CSS3, JavaScript, jQuery • Laravel Framework • Magento • WordPress • Joomla • Bootstrap • Get to work on live projects • Preferential involvement in multiple projects • Preferential involvement in taking higher responsibility on project • We will also assign you a dedicated mentor from the industry, to be your personal industry guide throughout the job search process • Payment Options • Full payment by bank transfer. • Web Developer can earn up to $1,500/week. • Standard Content • Well Paid & In-demand technical skills • Hands-on tutorials • Participation in a commercial project(s) • Work with senior staff • Full source code & DB access • Interview simulation & review CV • Provide reference • Industry connections & Soft skills training Conditions for cash back Candidate must have 100% attendance record throughout the program. Candidate must coordinate with us according to the roaster during training program. Contact Details: 021 035 7909 [email protected] https://www.instagram.com/p/B4jXIz7gUtD/?igshid=4oftuebz94mr
0 notes
Text
Follow Social Networking Swift 3 and Laravel 5 (Full Applications)
With Follow Social Networking Swift 3 and Laravel 5 you can easily and simply create your own personal social network. With My Social Network you can publish posts, read the posts of followings people, and more. Follow Social Networking built with Swift 3. The server side is built on object oriented Laravel 5 (PHP >= 5.6.4) with a MySQL database.
Video: https://youtu.be/s4f-owVBH-s
=========== Full application build for iOS 8+ with swift 3.
HOW TO SETUP:
Create push notification certificate ios: - read: http://ift.tt/2qPTrSN
Create pem file: - read: http://ift.tt/2wXs28n
After create pem file copy it to folder pem on server side with name: dev.pem
1. Open Follow.xcodeproj on Xcode - Change App bundle ID
2. Open file API_URL.swift : - Change service api : let API_DOMAIN
3. Open file Ultilities.swift : - Change contact email: let contact_email
4. Open Assets.xcassets - Change image for page slide: page1, page2, page3
5. Open Config.swift - Change : let group_app let uuid_app let user_id let token_app let user_avatar let user_name let is_login
6. On Xcode open tab : Capabilities - Enable Push Notifications
7. Config web api; open config/database.php file - Change info DB connect: ‘database’ => env(‘DB_DATABASE’, ’’), ‘username’ => env(‘DB_USERNAME’, ’’), ‘password’ => env(‘DB_PASSWORD’, ’’),
7. chmod 777 folder - storage - bootstrap
8. import DB: file database.sql
Done.
from CodeCanyon new items http://ift.tt/2xCUFVy via IFTTT https://goo.gl/zxKHwc
0 notes
Quote
Dev.to is Fast It is insane. Dev.to is capital-F Fast. It's so fast that it feels like a local web app, not one on the internet. I was exposed to Dev.to a long time ago but it had always been one-off articles, so the speed is less noticeable; when I actually went through to sign up for an account, edit my profile, etc. I noticed how ridiculously fast it is. My immediate thought was, what is Dev.to doing right that pretty much every other site on the internet right now is doing wrong? How can they be so fast? By comparison, it makes the sites of even internet giants (Reddit, Github, and even Hacker News!) feel like turtles. And it's not like Dev.to is small -- Alexa reports it at around the 8000~ range in global ranking (compared to HackerNoon at 4000~ or npmjs at 6000~ or so), and there's tons of content! Digging into it, it's a traditional Rails site with InstantClick I first started by viewing source and opening Chrome Dev Tools; and noticed that every page had full HTML rendered so it didn't seem like a React (or any other frontend framework) site. Then I noticed that whenever I hover any links, it sends a request to preload pages. I knew of a JS library called Turbolinks that did that, so I thought that might be it. Then I noticed the Dev.to site code is open source, so I checked it out and found its tech stack page and saw that InstantClick was the secret sauce. It works exactly as I observed -- it preloads the HTML output of hyperlinks as you hover them, and replaces the current page's HTML when you click on them, and adds some history.pushState() for good measure. This is the model content-based web apps should strive for Let's face it, big orgs/startups that manage content-based web sites with a modest amount of functionality/business logic almost always default to React for a frontend framework. Organizationally this makes sense, you have a big dev team working on the product, and a component-based frontend architecture is the most sensible way to work together on a big frontend codebase. But is it the best UX? One doesn't need to venture far from your typical popular media sites (Techcrunch, ESPN, etc.) to see them doing React or React-like behaviors -- your typical server-side-rendering of the first page, loading a JS bundle, hydrating the app on client JS framework, and then the next pages load in API calls, etc. In contrast, Dev.to simply prints the output HTML of the page from the server at each server endpoint, and it's only boosted by InstantClick preloading the page when you hover the links (and subsequently the new HTML replacing the current HTML to prevent a full browser page navigation). I argue that this is the model content-based sites, content-based web apps, including blogs, e-commerce web sites, etc. should be using in their development. Why does this make sense? We, as the whole tech industry, spent a decade (roughly from 2007 to 2017 or so) optimizing every part of the server side of web apps -- everything ranging from database performance (techniques like read replicas, sharding, and newer and newer generations of DB engines), caching (memcache, Redis, local web server caching), asynchronous work queues for writing data, loadbalancers and infinitely scaling web servers (with the advent of AWS), regions/availability zones and edge CDNs to be closer to users. Once we have everything, we really proceeded to nullify all that investment in server side performance optimization by putting a heavyweight frontend framework like React on the client side to work with those servers. Now to load a web site you need to load a 1mb JS bundle, have a spinner on the first page load of your site or web app, and let React handle this whole virtual DOM and calculate how to render everything at every point in time when anything changes states. We're right back to where we were in the 2000s when web sites/web apps were slow, when it was because we didn't have all those server side technologies and consumer internet connections were slow. Web sites take a few seconds to load now, just as it did in 2007; but for entirely different reasons. Isn't it a little sad for the end user, with all the advancement of technologies, the user experience stayed roughly the same (or worse)? But, component-based frontend development! Honestly, as someone who's not a fan of React, the only valid argument I agree with for doing a React frontend (and this is a huge one) is the organizational reason. In my 15 years of working in software teams, component-based frontend is really the most sensible way for a big team to work on a frontend codebase together and scale a frontend codebase; there's no way around it. Traditional MVC frameworks with templated views make it entirely too difficult to have any reasonable re-use of frontend code without some frankenstein monstrosity; and scaling a jquery frontend inevitably leads to spaghetti code. I believe it's one of the primary reasons React has taken off in tech startups; it's the best way to grow a dev team to work on frontend seriously. Maybe a new development paradigm is in order? How can we take advantage of server side generated HTML outputs in a web app, but also take advantage of component-based frontend development? Here's something I came up with literally just tonight, perhaps this could inspire you to try something similar? Frontend team develops in component-based framework of choice (React, Vue, Svelte, etc.). Frontend toolchain to build static HTML of each page based on components (This build happens both locally during development and on CI tool as well) -- this can continue to use Webpack, Rollup, or whatever folks prefer. Each built page takes in set of variables (similar to how templated views work in traditional MVC web apps). Frontend can mock this backend-provided data similar to how it mocks API responses for React frontends during development. Backend uses a traditional MVC architecture, with any language (Ruby, PHP, Python, Nodejs) and framework (Rails, Laravel, Django, CodeIgniter) of choice. Backend renders views by loading those prebuilt static HTML by page name, and passes in variables just as it does for templated views. Feature development workflow: Backend and frontend team members work on same branch for a feature, each check in their changes independently, when frontend checks in the components source code, CI tool runs the build toolchain and the generated static HTML for each view is then committed into repo as well. Frontend can continue to organize code in a similar React monorepo as they do right now, with reusable components and everything. Don't get me wrong, your React components can still react to clicks, moves, etc. and change states locally, you are free to still make AJAX requests in many valid use cases of it. All of that doesn't change. But page navigation should be left to and InstantClick and the server to generate the next page, when it's an entire page change. Your thoughts? I haven't given this work flow any more thoughts than it took to just write it all down, so curious to hear opinions of others.
http://damianfallon.blogspot.com/2020/04/devto-is-perfect-demonstration-of-how.html
0 notes
Text
Laravel 5.8 Tutorial From Scratch - e07 - SQLite Database - Laravel
Laravel 5.8 Tutorial From Scratch – e07 – SQLite Database – Laravel
Laravel 5.8 Tutorial From Scratch – e07 – SQLite Database – Laravel
[ad_1]
Let’s get the basics of working with a database in Laravel by setting up an SQLite database from scratch. Let’s also create a migration and a model for our customers.
For the best experience, follow along in our interactive school at https://www.coderstape.com
Resources Course Source Code https://github.com/coderstape/larav…
View On WordPress
#database configuration laravel#dotenv#laravel#laravel 5#laravel 5.8#laravel 5.8 install#laravel 5.8 new feature#laravel 5.8 what&039;s new#laravel connect db#laravel database#laravel database configuration#laravel database settings#laravel db settings#laravel for beginners#laravel from scratch#laravel from the ground up#laravel mysql json#laravel preview#laravel tutorial#php carbon immutable#php framework#php framework 2019#php what&039;s new 2019
0 notes
Text
Full Stack Developer job at mytruck.my Malaysia
mytruck.my – Malaysia No. 1 online platform for buying and selling of used and new trucks and lorries.
Our mission is reflected in our tagline ‘Connecting Truck Owners’ which means everything that we have done, are doing, and planning to do is geared towards making the selling and buying trucks a simple process for the buyers & sellers. Only when both buyers & sellers gain from the experience that this industry will thrive. Our goal is to become the premier online platform for buying & selling of trucks in ASEAN.
Our office is located at Sunway Velocity, Cheras, KL. We value the hard work put in by the team members and we reward base on merits and results. We encourage open communications between the team members and the sense of ownership in the work we do. We appreciate talents that can work in a team and also perform individually. We believe that integrity in a person is of utmost importance. We also believe that in everything we do, we must always strive for excellence. Never wait for things to happen, always have a sense of urgency and aim for progress.
If you’re interested to know more then check out our website at http://bit.ly/mytruckmyjobs
#mytruckmy #jomcarilori
We’re looking for a Full Stack developer who will take a key role on our team.
Our Full Stack developer must have knowledge and familiar with all layers in all stages of software development.
Someone who can go at it alone, if need be.
Someone who is comfortable working on both the front-end and back-end of our web application.
Someone who is expected to be able to deliver features completely on your own, designing your own DB structure and implementing the front-end & back-end.
Someone who is more superman than superman himself. So, are you the one?
Skills and Expertise
Design overall architecture of the web application.
Maintain quality and ensure responsiveness of applications.
Collaborate with the rest of the engineering team to design and launch new features.
Maintain code integrity and organization.
Experience working with graphic designers and converting designs to visual elements.
Understanding and implementation of security and data protection.
Highly experienced with back-end programming languages with preference in PHP with understanding of Laravel.
Development experience for both mobile and desktop.
Understanding of server-side languages.
Experience with cloud message APIs and usage of push notifications.
Knowledge of code versioning tools such as Git.
StartUp Jobs Asia - Startup Jobs in Singapore , Malaysia , HongKong ,Thailand from http://www.startupjobs.asia/job/40525-full-stack-developer-full-stack-developer-job-at-mytruck-my-malaysia Startup Jobs Asia https://startupjobsasia.tumblr.com/post/178299463399
0 notes