#how to pass form value to controller in laravel
Explore tagged Tumblr posts
Text
Laravel 5.8 Post Form Data From View to Controller Using Ajax
[ad_1] In this laravel tutorial I have explained how can we post form data from view to controller Using ajax in Laravel 5.8. I also explained how can we validate the form.
#Laravel5.8 #Laravel
1 – Create Controller (0:25) 2 – Create Route (1:05) 3 – Include jQuery for Ajax Function (7:40) 3 – Add Server Side Validation (17:02)
This laravel tutorial video is very good for beginners where they…
View On WordPress
#get data in controller laravel#how to pass form value to controller in laravel#how to send data from form to database in laravel#how to send form data to controller in laravel#Laravel#laravel pass data from view to controller#laravel pass request to controller#laravel post request from controller#laravel post route#laravel tutorial#laravel tutorial for beginners step by step#pass form data to controller laravel#send post data to controller laravel#view to controller laravel
0 notes
Text
300+ TOP LARAVEL Interview Questions and Answers
Laravel Interview Questions for freshers experienced :-
1. What is Laravel? An open source free "PHP framework" based on MVC Design Pattern. It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in creating a wonderful web application easily and quickly. 2. List some official packages provided by Laravel? Below are some official packages provided by Laravel Cashier: Laravel Cashier provides an expressive, fluent interface to Stripe's and Braintree's subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Cashier can handle coupons, swapping subscription, subscription "quantities", cancellation grace periods, and even generate invoice PDFs.Read More Envoy: Laravel Envoy provides a clean, minimal syntax for defining common tasks you run on your remote servers. Using Blade style syntax, you can easily setup tasks for deployment, Artisan commands, and more. Currently, Envoy only supports the Mac and Linux operating systems. Read More Passport: Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Alex Bilbie. Read More Scout: Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.Read More Socialite: Laravel Socialite provides an expressive, fluent interface to OAuth authentication with Facebook, Twitter, Google, LinkedIn, GitHub and Bitbucket. It handles almost all of the boilerplate social authentication code you are dreading writing.Read More 3. What is the latest version of Laravel? Laravel 5.8.29 is the latest version of Laravel. Here are steps to install and configure Laravel 5.8.29 4. What is Lumen? Lumen is PHP micro framework that built on Laravel's top components. It is created by Taylor Otwell. It is the perfect option for building Laravel based micro-services and fast REST API's. It's one of the fastest micro-frameworks available. 5. List out some benefits of Laravel over other Php frameworks? Top benifits of laravel framework Setup and customization process is easy and fast as compared to others. Inbuilt Authentication System. Supports multiple file systems Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel Scout. Eloquent ORM (Object Relation Mapping) with PHP active record implementation. Built in command line tool "Artisan" for creating a code skeleton ,database structure and build their migration. 6. List out some latest features of Laravel Framework Inbuilt CRSF (cross-site request forgery ) Protection. Laravel provided an easy way to protect your website from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are malicious attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. Inbuilt paginations Laravel provides an easy approach to implement paginations in your application.Laravel's paginator is integrated with the query builder and Eloquent ORM and provides convenient, easy-to-use pagination of database. Reverse Routing In Laravel reverse routing is generating URL's based on route declarations.Reverse routing makes your application so much more flexible. Query builder: Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings. read more Route caching Database Migration IOC (Inverse of Control) Container Or service container. 7. How can you display HTML with Blade in Laravel? To display html in laravel you can use below synatax. {!! $your_var !!} 8. What is composer? Composer is PHP dependency manager used for installing dependencies of PHP applications.It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. It provides us a nice way to reuse any kind of code. Rather than all of us reinventing the wheel over and over, we can instead download popular packages. 9. How to install Laravel via composer? To install Laravel with composer run below command on your terminal. composer create-project Laravel/Laravel your-project-name version 10. What is php artisan. List out some artisan commands? PHP artisan is the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. Here are the list of some artisian command. php artisan list php artisan help php artisan tinker php artisan make php artisan –versian php artisan make model model_name php artisan make controller controller_name 11. How to check current installed version of Laravel? Use php artisan –version command to check current installed version of Laravel Framework Usage: php artisan --version 12. List some Aggregates methods provided by query builder in Laravel? Aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurements such as a set, a bag or a list. Below is list of some Aggregates methods provided by Laravel query builder. count() Usage:$products = DB::table(‘products’)->count(); max() Usage:$price = DB::table(‘orders’)->max(‘price’); min() Usage:$price = DB::table(‘orders’)->min(‘price’); avg() Usage:$price = DB::table(‘orders’)->avg(‘price’); sum() Usage: $price = DB::table(‘orders’)->sum(‘price’); 13. Explain Events in Laravel? Laravel events: An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation, that allow us to subscribe and listen for events in our application.An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation, that allows us to subscribe and listen for events in our application. Below are some events examples in Laravel:- A new user has registered A new comment is posted User login/logout New product is added. 14. How to turn off CRSF protection for a route in Laravel? To turn off or diasble CRSF protection for specific routes in Laravel open "app/Http/Middleware/VerifyCsrfToken.php" file and add following code in it //add this in your class private $exceptUrls = ; //modify this function public function handle($request, Closure $next) { //add this condition foreach($this->exceptUrls as $route) { if ($request->is($route)) { return $next($request); } } return parent::handle($request, $next);} 15. What happens when you type "php artisan" in the command line? When you type "PHP artisan" it lists of a few dozen different command options. 16. Which template engine Laravel use? Laravel uses Blade Templating Engine. Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory. 17. How can you change your default database type? By default Laravel is configured to use MySQL.In order to change your default database edit your config/database.php and search for ‘default’ => ‘mysql’ and change it to whatever you want (like ‘default’ => ‘sqlite’). 18. Explain Migrations in Laravel? How can you generate migration . Laravel Migrations are like version control for your database, allowing a team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema. Steps to Generate Migrations in Laravel To create a migration, use the make:migration Artisan command When you create a migration file, Laravel stores it in /database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations. Open the command prompt or terminal depending on your operating system. 19. What are service providers in laravel? Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel’s core services are bootstrapped via service providers. Service provider basically registers event listeners, middleware, routes to Laravel’s service container. All service providers need to be registered in providers array of app/config.php file. 20. How do you register a Service Provider? To register a service provider follow below steps: Open to config/app.php Find ‘providers’ array of the various ServiceProviders. Add namespace ‘Iluminate\Abc\ABCServiceProvider:: class,’ to the end of the array. 21. What are Implicit Controllers? Implicit Controllers allow you to define a single route to handle every action in the controller. You can define it in route.php file with Route: controller method. Usage : Route::controller('base URI',''); 22. What does "composer dump-autoload" do? Whenever we run "composer dump-autoload" Composer re-reads the composer.json file to build up the list of files to autoload. 23. Explain Laravel service container? One of the most powerful feature of Laravel is its Service Container . It is a powerful tool for resolving class dependencies and performing dependency injection in Laravel. Dependency injection is a fancy phrase that essentially means class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods. 24. How can you get users IP address in Laravel? You can use request’s class ip() method to get IP address of user in Laravel. Usage:public function getUserIp(Request $request){ // Getting ip address of remote user return $user_ip_address=$request->ip(); } 25. What are Laravel Contracts? Laravel’s Contracts are nothing but set of interfaces that define the core services provided by the Laravel framework. 26. How to enable query log in Laravel? Use the enableQueryLog method: Use the enableQueryLog method: DB::connection()->enableQueryLog(); You can get an array of the executed queries by using the getQueryLog method: $queries = DB::getQueryLog(); 27. What are Laravel Facades? Laravel Facades provides a static like interface to classes that are available in the application’s service container. Laravel self ships with many facades which provide access to almost all features of Laravel’s. Laravel Facades serve as "static proxies" to underlying classes in the service container and provides benefits of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods of classes. All of Laravel’s facades are defined in the IlluminateSupportFacades namespace. You can easily access a Facade like so: use IlluminateSupportFacadesCache; Route::get('/cache', function () { return Cache::get('key'); }); 28. How to use custom table in Laravel Model? We can use custom table in Laravel by overriding protected $table property of Eloquent. Below is sample uses: class User extends Eloquent{ protected $table="my_custom_table"; } 29. How can you define Fillable Attribute in a Laravel Model? You can define fillable attribute by overiding the fillable property of Laravel Eloquent. Here is sample uses Class User extends Eloquent{ protected $fillable =array('id','first_name','last_name','age'); } 30. What is the purpose of the Eloquent cursor() method in Laravel? The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage. Example Usageforeach (Product::where('name', 'bar')->cursor() as $flight) { //do some stuff } 31. What are Closures in Laravel? Closures are an anonymous function that can be assigned to a variable or passed to another function as an argument.A Closures can access variables outside the scope that it was created. 32. What is Kept in vendor directory of Laravel? Any packages that are pulled from composer is kept in vendor directory of Laravel. 33. What does PHP compact function do? Laravel's compact() function takes each key and tries to find a variable with that same name.If the variable is found, them it builds an associative array. 34. In which directory controllers are located in Laravel? We kept all controllers in App/Http/Controllers directory 35. Define ORM? Object-relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages. 36. How to create a record in Laravel using eloquent? To create a new record in the database using Laravel Eloquent, simply create a new model instance, set attributes on the model, then call the save method: Here is sample Usage.public function saveProduct(Request $request ){ $product = new product; $product->name = $request->name; $product->description = $request->name; $product->save(); } 37. How to get Logged in user info in Laravel? Auth::User() function is used to get Logged in user info in Laravel. Usage:- if(Auth::check()){ $loggedIn_user=Auth::User(); dd($loggedIn_user); } 38. Does Laravel support caching? Yes, Laravel supports popular caching backends like Memcached and Redis. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the file system .For large projects it is recommended to use Memcached or Redis. 39. What are named routes in Laravel? Named routing is another amazing feature of Laravel framework. Named routes allow referring to routes when generating redirects or Url’s more comfortably. You can specify named routes by chaining the name method onto the route definition: Route::get('user/profile', function () { // })->name('profile'); You can specify route names for controller actions: Route::get('user/profile', 'UserController@showProfile')->name('profile'); Once you have assigned a name to your routes, you may use the route's name when generating URLs or redirects via the global route function: // Generating URLs... $url = route('profile'); // Generating Redirects... return redirect()->route('profile'); 40. What are traits in Laravel? Laravel Traits are simply a group of methods that you want include within another class. A Trait, like an abstract classes cannot be instantiated by itself.Trait are created to reduce the limitations of single inheritance in PHP by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. Laravel Triats Exampletrait Sharable { public function share($item) { return 'share this item'; } } You could then include this Trait within other classes like this: class Post { use Sharable; } class Comment { use Sharable; } Now if you were to create new objects out of these classes you would find that they both have the share() method available: $post = new Post; echo $post->share(''); // 'share this item' $comment = new Comment; echo $comment->share(''); // 'share this item' 41. How to create migration via artisan? Use below commands to create migration data via artisan. php artisan make:migration create_users_table 42. Explain validations in Laravel? In Programming validations are a handy way to ensure that your data is always in a clean and expected format before it gets into your database. Laravel provides several different ways to validate your application incoming data.By default Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate all incoming HTTP requests coming from client.You can also validate data in laravel by creating Form Request. 43. Explain Laravel Eloquent? Laravel’s Eloquent ORM is one the most popular PHP ORM (OBJECT RELATIONSHIP MAPPING). It provides a beautiful, simple ActiveRecord implementation to work with your database. In Eloquent each database table has the corresponding MODEL that is used to interact with table and perform a database related operation on the table. Sample Model Class in Laravel.namespace App; use Illuminate\Database\Eloquent\Model; class Users extends Model { } 44. Can laravel be hacked? Answers to this question is NO.Laravel application’s are 100% secure (depends what you mean by "secure" as well), in terms of things you can do to prevent unwanted data/changes done without the user knowing. Larevl have inbuilt CSRF security, input validations and encrypted session/cookies etc. Also, Laravel uses a high encryption level for securing Passwords. With every update, there’s the possibility of new holes but you can keep up to date with Symfony changes and security issues on their site. 45. Does Laravel support PHP 7? Yes,Laravel supports php 7 46. Define Active Record Implementation. How to use it Laravel? Active Record Implementation is an architectural pattern found in software engineering that stores in-memory object data in relational databases. Active Record facilitates the creation and use of business objects whose data is required to persistent in the database. Laravel implements Active Records by Eloquent ORM. Below is sample usage of Active Records Implementation is Laravel. $product = new Product; $product->title = 'Iphone 6s'; $product->save(); Active Record style ORMs map an object to a database row. In the above example, we would be mapping the Product object to a row in the products table of database. 47. List types of relationships supported by Laravel? Laravel support 7 types of table relationships, they are One To One One To Many One To Many (Inverse) Many To Many Has Many Through Polymorphic Relations Many To Many Polymorphic Relations 48. Explain Laravel Query Builder? Laravel's database query builder provides a suitable, easy interface to creating and organization database queries. It can be used to achieve most database operations in our application and works on all supported database systems. The Laravel query planner uses PDO restriction necessary to keep our application against SQL injection attacks. 49. What is Laravel Elixir? Laravel Elixir provides a clean, fluent API for defining basic Gulp tasks for your Laravel application. Elixir supports common CSS and JavaScript preprocessors like Sass and Webpack. Using method chaining, Elixir allows you to fluently define your asset pipeline. 50. How to enable maintenance mode in Laravel 5? You can enable maintenance mode in Laravel 5, simply by executing below command. //To enable maintenance mode php artisan down //To disable maintenance mode php artisan up 51. List out Databases Laravel supports? Currently Laravel supports four major databases, they are :- MySQL Postgres SQLite SQL Server 52. How to get current environment in Laravel 5? You may access the current application environment via the environment method. $environment = App::environment(); dd($environment); 53. What is the purpose of using dd() function iin Laravel? Laravel's dd() is a helper function, which will dump a variable's contents to the browser and halt further script execution. 54. What is Method Spoofing in Laravel? As HTML forms does not supports PUT, PATCH or DELETE request. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method: To generate the hidden input field _method, you may also use the method_field helper function: In Blade template you can write it as below {{ method_field('PUT') }} 55. How to assign multiple middleware to Laravel route ? You can assign multiple middleware to Laravel route by using middleware method. Example:// Assign multiple multiple middleware to Laravel to specific route Route::get('/', function () { // })->middleware('firstMiddleware', 'secondMiddleware'); // Assign multiple multiple middleware to Laravel to route groups Route::group(], function () { // }); Laravel Questions and Answers Pdf Download Read the full article
0 notes
Text
Uploading Images to Cloudinary with Laravel (sponsor)
Sponsor / November 13, 2017
Uploading Images to Cloudinary with Laravel (sponsor)
Images are an essential part of any web application. They have the power to create an emotional response in the audience, which is worth its weight in gold. Our brain is designed to interpret images much quicker than text, so when developing a website, it is imperative to take your images seriously.
In this tutorial, I will introduce you to image services offered by Cloudinary for uploading images in Laravel. We will focus on uploading images to the Cloudinary server in Laravel application.
Cloudinary is the end-to-end image and video management solution, which also offers robust, highly reliable cloud storage for all your media.
What We will Build
In this tutorial, we will upload images to Cloudinary using jrm2k6/cloudder package. This package will do the heavy lifting for us and make it easy to interact with Cloudinary API.
Sign up For a Free Cloudinary Account
Before we start installing Laravel, go to Cloudinary and sign up for a free Cloudinary account.
This will give you the necessary credentials to access and interact with Cloudinary functionalities. Once you have signed up, log in and view your dashboard. It should be similar to this:
Take note of your account details Cloud name, API Key, API Secret because you will need them within your .env file:
CLOUDINARY_API_KEY = 'Your key' CLOUDINARY_API_SECRET = 'Your secret' CLOUDINARY_CLOUD_NAME = 'Your cloud name'
You are almost ready to start utilizing some of the amazing services and functionalities offered by Cloudinary.
Install Laravel
Laravel utilizes Composer to manage its dependencies. So before using Laravel, make sure you have Composer installed on your machine.
You can download and install Laravel via:
Laravel installer
Composer create-project.
For the sake of this tutorial, let’s proceed by using the second option. So run :
composer create-project --prefer-dist laravel/laravel laravel-upload-tut
This will create a Laravel project called laravel-upload-tut in your development directory.
Next, install jrm2k6/cloudder package using composer:
composer require jrm2k6/cloudder:0.4.*
Now open config\app.php file and add the following service provider and aliases in respective array:
'providers' => array( 'JD\Cloudder\CloudderServiceProvider' ); 'aliases' => array( 'Cloudder' => 'JD\Cloudder\Facades\Cloudder' );
Run the following command to publish:
php artisan vendor:publish --provider="JD\Cloudder\CloudderServiceProvider"
The command above will generate a cloudder configuration file for you in the following path config/cloudder.php
You can change the following settings (optional) with corresponding values from your dashboard:
CLOUDINARY_BASE_URL CLOUDINARY_SECURE_URL CLOUDINARY_API_BASE_URL
Start the PHP’s built-in development server to serve your application:
php artisan serve
Creating a Controller and Route
We are getting close; the next thing is to create a controller that will handle the image upload request:
php artisan make:controller ImageUploadController
Open app\Http\Controllers and add :
<?php namespace App\Http\Controllers; use JD\Cloudder\Facades\Cloudder; use Illuminate\Http\Request; class ImageUploadController extends Controller { public function home() { return view('home'); } }
This function will render the view for uploading our images. We will create this view in a bit. To handle image upload, let’s add another function uploadImages()
<?php ... class ImageUploadController extends Controller { public function home() { ... } public function uploadImages(Request $request) { $this->validate($request,[ 'image_name'=>'required|mimes:jpeg,bmp,jpg,png|between:1, 6000', ]); $image_name = $request->file('image_name')->getRealPath();; Cloudder::upload($image_name, null); return redirect()->back()->with('status', 'Image Uploaded Successfully'); } }
Here, we handled validation of an uploaded image and ensured that the file size is between 1kb and 6000kb. Then we used Cloudder::upload($image_name, null) to handle the actual upload of the image to Cloudinary account.
For the upload routes, open routes/web.php file and add the following:
<?php Route::get('/', 'ImageUploadController@home'); Route::post('/upload/images', [ 'uses' => 'ImageUploadController@uploadImages', 'as' => 'uploadImage' ]);
The next thing to do is to create a view file for our example application. So head over to resources/views and create home.blade.php file. Fill it with :
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width"> <title>Cloudinary Image Upload</title> <meta name="description" content="Prego is a project management app built for learning purposes"> <link rel="stylesheet" href="http://ift.tt/2apRjw3"> <link rel="stylesheet" href=""> </head> <body> <div class="container" style="margin-top: 100px;"> <div class="row"> <h4 class="text-center"> Upload Images </h4> <div class="row"> <div id="formWrapper" class="col-md-4 col-md-offset-4"> <form class="form-vertical" role="form" enctype="multipart/form-data" method="post" action=""> @if(session()->has('status')) <div class="alert alert-info" role="alert"> </div> @endif <div class="form-group"> <input type="file" name="image_name" class="form-control" id="name" value=""> @if($errors->has('image_name')) <span class="help-block"></span> @endif </div> <div class="form-group"> <button type="submit" class="btn btn-success">Upload Image </button> </div> </form> </div> </div> </div> </div> </body> </html>
To spice our page up a little, let’s add navigation:
<!DOCTYPE html> <html> <head> ... </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Cloudinary Image Upload</a> </div> </div> </nav> ... </body> </html>
You will notice that we included a stylesheet in the home.blade.php file. Let’s now create public/css/style.css and add:
#formWrapper { border: 2px solid #f5f5f5; padding: 20px; }
By now, your page should look similar to this:
You can go ahead and upload any image now.
There you have it, uploading images to Cloudinary from the Laravel application is as simple as that.
##Bonus: Persisting Image Delivery URLs
The objective of this tutorial was to show you how to upload images to Cloudinary using Laravel. We have been able to achieve this already, but you might want to save the URL of the uploaded image in your database and be able to view all of them, as well.
Let’s create a model for this purpose. The fastest way to create a model is to use the following command, with a parameter that you can use to specify the model name. So in our case, we will create an Upload model.
php artisan make:model Upload -m
Once you are done, you will find a new file as app/Upload.php and migration file associated with the model for our database schema.
Now open the migration file generated and edit it to reflect our database schema:
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUploadsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('uploads', function (Blueprint $table) { $table->increments('id'); $table->string('image_name'); $table->string('image_url'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('uploads'); } }
##Database Set Up Open the .env file and add your database details
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=Your-database-name DB_USERNAME=Your-database-username DB_PASSWORD=Your-database-password
##Migrating and Creating Table You can go ahead and run the migration with:
php artisan migrate
If you hit the following error when trying to run the migration command, it’s because you are running an older version of MySQL:
[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
You can read more about it here. But a quick fix is to drop the database and re-create it. Then you have to edit your AppServiceProvider.php file and set a default string length inside the boot method:
use Illuminate\Support\Facades\Schema; public function boot() { Schema::defaultStringLength(191); }
You can now run the migration command again and everything should be fine.
In order to obtain and save the image URL uploaded to Cloudinary, we will need to edit the logic within ImageUploadController. So can go ahead and replace uploadImages() function with this:
public function uploadImages(Request $request) { $this->validate($request,[ 'image_name'=>'required|mimes:jpeg,bmp,jpg,png|between:1, 6000', ]); $image = $request->file('image_name'); $name = $request->file('image_name')->getClientOriginalName(); $image_name = $request->file('image_name')->getRealPath();; Cloudder::upload($image_name, null); list($width, $height) = getimagesize($image_name); $image_url= Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height"=>$height]); //save to uploads directory $image->move(public_path("uploads"), $name); //Save images $this->saveImages($request, $image_url); return redirect()->back()->with('status', 'Image Uploaded Successfully'); }
And add this new method to persist the image URL and name into the database:
public function saveImages(Request $request, $image_url) { $image = new Upload(); $image->image_name = $request->file('image_name')->getClientOriginalName(); $image->image_url = $image_url; $image->save(); }
To access the uploaded image on the homepage, we need to pass the image object to the view:
<?php namespace App\Http\Controllers; use App\Upload; ... class ImageUploadController extends Controller { public function home() { // add this $images = Upload::all(); return view('home', compact('images')); } }
To display the images, we also will need to edit the home.blade.php file:
<!DOCTYPE html> <html> <head> ... </head> <body> ... <div class="row" id="displayImages"> @if($images) @foreach($images as $image) <div class="col-md-3"> <a href="" target="_blank"> <img src="" class="img-responsive" alt=""> </a> </div> @endforeach @endif </div> </div> </div> </body> </html>
So we checked if the $images object is found within the view and loop through it to display the uploaded image.
And add this to the style.css file:
#displayImages { margin: 30px 0; }
You will see the images being displayed immediately after it has been uploaded successfully to Cloudinary:
Conclusion
Cloudinary is a reliable source for storage when it comes to images in particular and any other media files in general. As shown in this tutorial, uploading images to the Cloudinary server from your Laravel web application is so simple to achieve. You can check out Cloudinary for more information on how to manipulate your images dynamically to fit any design.
—
Many thanks to Cloudinary for sponsoring Laravel News this week.
via Laravel News http://ift.tt/2AACDDV
0 notes
Text
Codeigniter User Registration Form With Email Notification
New Post has been published on https://www.eknowledgetree.com/codeigniter/codeigniter-user-registration-form-with-email-notification/
Codeigniter User Registration Form With Email Notification
Codeigniter is one of the best MVC frameworks in PHP, creating a project in Codeigniter framework is simple, when compared to other frameworks called Yii framework and laravel framework. If we plan to create a project, the first thing we need to create Codeigniter user registration form, in every project when it moves to development stage, first thing we create registration page to get leads.
We all know Codeigniter is MVC Framework which stands for Model, Veiw and controller. So now you understand what files we need, let’s jump into the Codeigniter user registration form. First we need to create view for registration page , which display in frontend. Let’s create view as registration.php under view folder. If you have good knowledge in HTML and CSS you can design your view using bootstrap, which looks beautiful and mobile friendly. Now I am sharing registration.php file which I created for this demo.
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.min.js"></script> <script type="text/javascript" src="<?php echo base_url();?>js/uservalidation.js"></script> <h5 class="head">Codeigniter User Registration </h5> <div class="d-form bdr mgn0"> <div class=""> </div> <div> <form method="post" action="insertnewuser" id="form" > <div class="white-shadow content-inner-block"> <span style="font-weight:normal;color:#333333;text-align:right"> <font color="red">*</font> Marked fields are compulsory </span> </div> <div class="form-group"> <label for="txtLoginid">Name <span class="style1">*</span> </label> <input name="txtName" type="text" size="25" id="txtName" placeholder="First Name" class="form-control" value="<?php echo set_value('txtName');?>" /> <span id="nameError" class="red"></span> <span style="color:red"><?php //echo form_error('txtName');?></span> </div> <div class="form-group"> <label for="txtLoginid">Email <span class="style1">*</span> </label> <input name="txtEmail" type="email" size="25" id="txtEmail" placeholder="Enter email" class="form-control" value="<?php echo set_value('txtEmail');?>" /> <span id="emailError" class="red"></span> <span style="color:red"><?php echo form_error('txtEmail');?></span> </div> <div class="form-group"> <label for="txtEmailConf">Confirm Email <span class="style1">*</span></label> <input name="txtEmailConf" type="email" size="25" id="txtcompanyname" placeholder="Confirm email" class="form-control" value="<?php echo set_value('txtEmailConf');?>" /> <span id="verifyemailerror" class="red"></span> <span style="color:red"><?php echo form_error('txtEmailConf');?></span> </div> <div class="radio"> <label> <input type="radio" id="individual" name="usertype" value="user">Individual </label></div> <div class="radio"> <label> <input type="radio" id="dealerdisplay" name="usertype" value="dealer">Dealer </label> <span style="color:red"><?php echo form_error('usertype');?></span> <span id="usertypeError" class="red"></span> </div> <div class="form-group"> <label for="txtcompanyname">Company Name</label> <input name="txtcompanyname" type="text" size="25" id="txtcompanyname" placeholder="Enter Company name" class="form-control" value="<?php echo set_value('txtcompanyname');?>" /> </div> <div class="form-group"> <label for="txtPassword">Create a Password <span class="style1">*</span></label> <input name="txtPassword" type="password" size="25" id="txtPassword" placeholder="Enter password" class="form-control" value="<?php echo set_value('txtPassword');?>" /> <span style="color:red"><?php echo form_error('txtPassword');?></span> <span id="passwordError" class="red"></span> </div> <div class="form-group"> <label for="txtConfirmPassword">Confirm your Password <span class="style1">*</span></span></label> <input name="txtConfirmPassword" type="password" size="25" id="txtConfirmPassword" placeholder="Confrim password" class="form-control" value="<?php echo set_value('txtConfirmPassword');?>" /> <span style="color:red"><?php echo form_error('txtConfirmPassword');?></span> <span id="pwVerifiedError" class="red"></span> </div> <div class="form-group"> <label for="txtMobile">Mobile No. <span class="style1">*</span></label> <input name="txtMobile" type="text" size="25" id="txtMobile" maxlength="10" class="form-control" value="<?php echo set_value('txtMobile');?>" /> <span style="color:red"><?php echo form_error('txtMobile');?></span> </div> <div class="form-group"> <label for="txtcity">City Name <span class="style1">*</span></label> <input name="txtcity" type="text" size="25" id="txtcity" maxlength="10" class="form-control" value="<?php echo set_value('txtcity');?>" /> <span style="color:red"><?php echo form_error('txtcity');?></span> <span id="cityError" class="red"></span> </div> <div class="checkbox"> <label> <input id="checkbox" type="checkbox" name="checkbox" onclick="if(!this.form.checkbox.checked)alert('You must agree to the terms first.');return false"/> I have read and agree with the <a target="_blank" href="<?php echo base_url();?>user/autofliq_terms">User Agreement and Privacy Policy</a> </label> </div> <button type="submit" class="btn btn-default" name="btnRegister">Submit</button> </form> </div> </div>
Now in the above code we simple created html form using Div’s, and also we added php tags , here
<?php code here .. ?>
Which is php opening and closing braces in between we can write our php code, here you find two major php code i.e. 1) set_value(); which helps you to set value to the field 2) form_error(); which show form error, when value is missing or wrong typo. Now let’s move to controller file , let’s create controller name as user.php and create function as below.
public function insertnewuser() trim'); $this->form_validation->set_rules('txtConfirmPassword','Password Confirmation', 'required
Don’t understand above code? Ok then let’s debug each and every line, after creating the function, first you need to load required libraries for your validations and email. • For better validation, Codeigniter have inbuilt library for validation and also provide some decent features to restrict cross site scripting. • You can see syntax for validation as
$this->form_validation->set_rules();
Now your validation filed looks as below. If your inputs are wrong it will move to your view registration.php and again you need to enter the valid values. Now if the values you entered are all valid your data will move to model function which looks like below.
$insertdata=$this->user_service->insertuserrecord();
And once your data moved to model function insertuserrecord(), the insert code looks like below.
public function insertuserrecord() $this->load->helper('string'); $name=$this->input->post('txtName', TRUE); $email=$this->input->post('txtEmail', TRUE); $usertype=$this->input->post('usertype',TRUE); $companyname=$this->input->post('txtcompanyname',TRUE); $password=$this->input->post('txtPassword',true); $pass_key=md5($this->input->post('txtPassword',TRUE)); $Mobilenumber=$this->input->post('txtMobile',TRUE); $city=$this->input->post('txtcity',TRUE); $key=random_string('alnum',5); $insertStatus=$this->db->insert('autoflip_user',array('firstName'=>$name ,'emailid'=>$email,'usertype'=>$usertype,'company_name'=>$companyname,'password'=>$password, 'pass_key'=>$key,'pass_encryption'=>$pass_key ,'mobilenumber'=>$Mobilenumber,'city'=> $city)); return $insertStatus;
After inserting data to database, we simply return $insertStatus; variable to controller again. Now let’s move to controller again and write code for email notification after successful user registration, let’s check how code looks in controller.
$this->load->library('email'); $config = array( 'mailtype' => 'html', 'charset' => 'utf-8', 'priority' => '1' ); $this->email->initialize($config); $this->email->from($sender_mail,'AutofliQ'); $this->email->to($mail); $this->email->cc('[email protected]'); $this->email->subject('Welcome To AutofliQ'); $message=$this->load->view('user/map_mail_format',$data,TRUE); $this->email->message($message); $this->email->send();
In this code we simply calling inbuilt email library from Codeigniter core files and initialize email , for every email , we have From, To ,CC , SUBJECT, BODY . In the same format we have functions in the email library, just we need to pass the parameters to send email notifications to registered user.
0 notes
Text
What's New in Laravel 5.5
At the time of this writing, Laravel 5.5 is not released yet. It is slated, as the next major release, for release in July 2017. To play around with new features and changes, you need to grab the dev release of Laravel using this Laravel Installer command:
laravel new project --dev
Get Ahead with PHP 7.0+
Laravel 5.5 will require PHP 7.0+. Along with developer features, PHP 7 includes speed improvements which will decrease CPU load by half. So, you should definitely make this upgrade. And if you are using Laravel 5, making this upgrade will be a lot easier since you using the latest version of PHP.
The Next LTS (Long Term Support) Release
After Laravel 5.1, Laravel 5.5 is scheduled to be the next LTS release. This includes two years of bug fixes and three years of security updates.
Welcome Back: Whoops!
Whoops, an error-handling framework, which used to be used by Laravel 4, was removed with the release of Laravel 5.0. But with Laravel 5.5, it's coming back pre-installed. What Whoops actually does is that it makes the annoying PHP errors and exceptions a little less annoying by changing how they appear. As you can see in the image that it sports the lines of the file in which the error or exception occurred and traces back the operation till inception. And not forgetting to mention, it has zero dependencies (currently('pre-laravel-55')).
"vendor:publish" Gets a Provider Prompt
In previous versions of Laravel, running the vendor:publish command will publish views, configs, migrations and other resources of all vendors. But in Laravel 5.5, running this command will prompt you to select a provider or tag, making it easier to publish only the ones you want. You can also bypass this prompt by specifying the --all' or '--provider' flag with thepublish` command.
Email Themes
Laravel 5.5 adds the ability to specify a custom theme directly to Mailable classes. You can create a CSS style-sheet like this:
touch resources/views/vendor/mail/html/themes/batman.css
And then specify this filename as a property in your Mailable class.
class SendInvoice extends Mailable { protected $theme = 'batman'; ... }
Rendering Mailables to the Browser
It can be tedious to test your email templates across email clients. One way to test them is to render them to the browser so that you can make instant changes. But it is not an easy task. Luckily, Laravel 5.5 adds the facility to display them directly from your routes.
You can create a Mailable like this:
php artisan make:mail UserWelcome --markdown=emails.user.subscription.canceled
And then render it through a route:
Route::get('/no/way', function () { return new App\Mail\UserSubscriptionCanceled(); });
There are other tools like Litmus, which solve this problem, but they are pretty expensive relative to this tediously trivial task.
Fresh Migrations
Laravel 5.5 adds another Artisan command to the migrate: namespace. This is similar to migrate:refresh but rather than rolling back your existing migrations, it drops all tables and migrates them from start. The difference between rolling back migrations and dropping tables is that rolling back migrations runs the drop method for each of them. Whilst, the migrate:fresh command simply drops all off of the tables and starts from scratch.
Automatic Package Discovery
In Laravel 5.4 and all versions before, pulling a Laravel package required registering its service providers and adding aliases. Laravel 5.5 adds the ability for packages to automatically register service providers and add aliases through the package's composer.json file like this:
"extra": { "laravel": { "providers": [ "The\\Dark\\Knight\\BatmanServiceProvider" ], "aliases": { "Bar": "The\\Dark\\Knight\\Batman" } } }
If you are a package developer, then things can't be much easier for your package users.
Frontend Presets
Out of the box, Laravel includes some CSS and JavaScript scaffolding to help accelerate coding the nitty-gritty. Although you could remove them and start over with your personal preferences, the suggestion was only limited to the Vue framework. Laravel 5.5 introduces 3 frontend presets: Bootstrap, Vue, React and an option choose your own. With Vue being the default preset, you can change the preset to react using this command:
php artisan preset react
You can change react in the above command to vue, bootstrap or none based on your preference.
Error Pages: Design Improvement
In Laravel 5.5, a little change is made in the design of the error pages like 404 or 50* errors: there are some design additions with Flexbox getting the error message centered on the page.
Before Laravel 5.5:
In Laravel 5.5:
Custom Error Reporting
Laravel 5.5 adds support for defining a report method on any custom exception. In Laravel 5.4, you had to check in the Handler class's report method if a particular exception was thrown. So that you could do something like send an email or report to your app's monitoring service. You were doing something like this:
... class Handler extends ExceptionHandler { ... public function report(Exception $exception) { if ($exception instanceof CustomException) { // Send email } parent::report($exception); } }
But with Laravel 5.5, you can get rid of this and register the report method on your custom exception class. Laravel checks to see if there is a report method on your exception class and if it does: calls it.
Streamlined Request Validation
Laravel 5.5 comes with two changes to Request feature. One is that you can now directly call the validate method on your Request instance. So instead of using the controller validator, you can call the validator on your Request instance. You also no longer need to pass the request as the first argument to the validator. Here is an example:
... public function store() { request()->validate([ 'title' => 'required', 'body' => 'required' ]); return Post::create(request(['title', 'body'])); }
The second change made is that the validator returns the request data which you can store in a variable and pass on to the create method of the model.
... public function store() { $post = request()->validate([ 'title' => 'required', 'body' => 'required' ]); // $data = request()->only('title', 'body'); return Post::create($post); }
You need to be careful with this since the data returned by the validator will only contain the fields defined in the rules. This adds a little security but you can loose data if some fields were not defined rules for. To avoid this trap, you can add the field with an empty rule like this:
public function store() { $post = request()->validate([ 'title' => 'required', 'body' => 'required', 'fieldWithNoRules' => '', 'andAnotherOne' => '' ]); // $data = request()->only('title', 'body'); return Post::create($post); }
Exception Helper Functions
Coming to Laravel 5.5 are two new helper functions to help you throw exceptions more elegantly. They are: throw_if and throw_unless, and they do exactly what they say. If you want to throw an exception based on a condition then these may help you reduce a conditional block to a single line. They both accept three arguments with the third being optional. First one is a boolean, second is the exception class and third is the exception message passed in case if you didn't pass with the instantiation of the exception in the second argument. throw_if throws the exception if the boolean is positive and throw_unless throws the exception when the boolean is negative. Here are the examples:
// For `throw_if: $foo = true; throw_if($foo, new BarException('Foo is true')); // or throw_if($foo, BarException::class, 'Foo is true'); // For `throw_unless: $phoo = false; throw_unless($phoo, new BazException('Phoo is false')); // or throw_unless($phoo, BazException::class, 'Phoo is false');
Custom Validation Rules
Laravel 5.5 is coming with a new feature for adding custom validation rules. Custom validation rules are nothing new but with Laravel 5.5 you can have a dedicated class to handle the validation. To define a custom validation rule, you need to create a class with two methods: passes and message. You can place this class anywhere like in the App\Rules namespace. The passes method accepts two arguments: attribute and value, which you can use to validate the field.
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class CustomRule implements Rule { /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { // must return true or false for the validation to pass or fail } /** * Get the validation error message. * * @return string */ public function message() { // return a string here for the failing condition } }
Your custom rule should implement the Laravel's Illuminate\Contracts\Validation\Rule contract. You can use this custom validation rule anywhere like in a Form Request class or in the controller validator or the validator from the Request instance. If you are using a custom rule then you can't pass a string with rules separated by a comma. You need to pass each rule as a single element grouped in an array like this:
$request->validate([ 'someField' => [ 'required', 'min:4', new CustomRule() ] ]);
You may also inject any dependency to the constructor if you want. This class-based approach makes custom validation a lot easier.
Model Factory Generators
In Laravel 5.5 you can easily generate model factories with a new Artisan command called make:factory. Here is an example:
php artisan make:factory PostFactory
This will make a new file called PostFactory.php in the database/factories folder. What makes it a lot better is that you can also generate a factory while making a model.
php artisan make:model Post -f
You may also pass the -c flag to add a controller and the -m flag to add a migration. This will help in quickly whipping up a resource.
Miscellany
One minor change is that if you forget to include the CSRF field in a form then it presents you with better inactivity error page. So, if you see something like that, then be sure that it's related to CSRF.
There is another minor change that will help you in building APIs. Now you get a JSON stack trace rather than HTML markup if an error occurs. This makes it a lot prettier to look at rather than the ugly markup if you are using a tool like Postman.
Conclusion
I hope this guide gets you prepared for the forthcoming goodness. So, This is all there is coming to Laravel 5.5.
Happy Coding!
via Scotch.io http://ift.tt/2sfOiDK
0 notes
Text
Build a Realtime CRUD App with Vue & deepstream
Vue is the JavaScript UI tool that parades itself as progressive because it is approachable so one can get started in just a day. On the other hand, it has every feature to cater for your front-end needs, making it versatile.
Realtime technologies are gradually taking a new shape; realtime servers now serve as an abstraction for handling realtime related tasks. deepstream is an open, free and blazingly fast realtime server that you can install on your machine.
This article demonstrates who we can build realtime apps using deepstream and Vue as our front end tool. The image below is a GIF of what we are up to:
Before we get dirty with codes, let's have a reason to do so.
Why Vue
Vue is so far, in my humble opinion, the simplest UI library out in the wild to get your hands dirty with. It is easy to get started and handles most of the tough concepts that come in mind when considering a UI library. These includes: data binding, server-side rendering, state management.
Vue acts on the complexity of the existing UI library and simplifies those complexities to make our lives less frustrating as software engineers. It also has been backed by one of our favorite backend tool, Laravel -- making integration straightforward. This of course does NOT mean you cannot integrate with any other backend platform.
Why deepstream
deepstream is a standalone server -- faster than most of the our realtime solutions -- that allows you to provision realtime server using persisted state as Data Sync, pub/sub pattern as events or request/response pattern as RPCs.
With these varieties of options, you are assured that deepstream can integrate in whatever nature of app you are building. Including chats, realtime news updates, stock information, CRUD/CMS apps, data visualization, data monitoring, etc.
Setup Vue and deepstream
Installing both Vue and deepstream is quite a straightforward process; few commands on your CLI and you're good to go.
deepstream can be installed on Linux, Windows, and OSX; it can also be installed using Docker and npm. For this article, we will download deepstream for our OS. Unzip the file and run the following command on the unzipped directory to start the server:
./deepstream
vue-cli is a CLI tool that makes scaffolding a Vue project easy and fast. We need to install this CLI tool then we can use the tool to create a new project for our demo app:
npm install -g vue-cli
The CLI tool is installed globally so we can access it from anywhere in our machine. Vue project scaffolds come in different templates, we need something simple and the following command will do just that for us:
vue init webpack my-project
Just CRUD with Vue
Before we attempt a realtime app, let's create a platform for that first. A CRUD (Create, Read Update and Delete) app for managing books will be a good idea.
Creating
The App.vue file in the src folder is our main and only component which is enough for what we are trying to build. Open the file and create a simple form:
<!-- ./src/App.vue --> <template> <div id="app"> <h1> </h1> <h3>New Book</h3> <form v-on:submit.prevent="onSubmit"> <div> <input name="title" type="text" placeholder="title" v-model="book.title" /> </div> <div> <input name="year" type="text" placeholder="year" v-model="book.year" /> </div> <div> <input name="author" type="text" placeholder="author" v-model="book.author" /> </div> <div> <label for="read">Read?</label> <input type="checkbox" v-model="book.read" id="read" name="read" /> </div> <button v-if="updating">Update</button> <button v-else>Add</button> </form> </div> </template> <script> export default { name: 'app', data () { return { title: 'My Books Manager', updating: false, book: { title: '', year: '', author: '', read: false } } } } </script>
The file App.vue is known as Vue's Single File Component which is a great strategy from structuring Vue apps by allowing each component to be stored in a file while its template, style, and logic live in the file.
We have a basic form with Vue bindings. Each of the form control is bound to a property (using v-model) in the book object returned by Vue's data method. The method also returns a title which we use as the app's header and an updating flag which we use to toggle Add and Update buttons in the form. The toggle is achieved using Vue's v-if...v-else directives.
When the button(s) is clicked, an onSubmit method will be called because that is what the form's submit event binding is bound to. We need to create this method:
export default { name: 'app', data () { return { // . . . updateIndex: 0, books: [], book: { title: '', year: '', author: '', read: false } } }, methods: { onSubmit() { if(this.updating) { this.onUpdate(); return; } this.books.push(this.book); this.book = { title: '', year: '', author: '', read: false } } } }
onSubmit will check if we are updating or not. If we are updating, it would delegate to another method, onUpdate, to handle updating. Otherwise, it would push the new values to the books array.
Reading
The books array can be iterated and its values printed using a table. The iteration is achievable using the v-for Vue directive as show:
<template> <div id="app"> <h1> </h1> <h3>New Book</h3> <!-- For markup truncated --> <h3>All Books</h3> <table> <tr> <th>Title</th> <th>Year</th> <th>Author</th> <th>Read</th> <td>Update</td> <td>Delete</td> </tr> <tr v-for="(b, index) in books"> <td></td> <td></td> <td></td> <td v-if="b.read">✓</td> <td v-else> </td> <td v-on:click.prevent="onEdit(index)"><a>✎</a></td> <td v-on:click.prevent="onDelete(index)"><a>✗</a></td> </tr> </table> </div> </template>
Something extra to the table's data rows -- two links to handle editing (not updating) and deleting a record. Each of them calls the onEdit and onDelete methods respectively. You can start using the form and see the results appear in the table:
Updating
Updating takes two stages -- selecting the record from the table that we need to update which will make it appear in the form and mutating the array to update the value.
The onEdit handler is responsible for the first stage:
data () { return { updating: false, updateIndex: 0, books: [], book: { title: '', year: '', author: '', read: false } } }, methods: { // . . . onEdit(index) { this.updating = true; this.updateIndex = index; this.book = this.books[index]; }, }
onEdit first raises the updating flag, then sets updateIndex to the index being edited and the replaces the book model with the record found in the index being updated.
updateIndex is used to keep track of what is being updated when onUpdate is called:
onUpdate() { this.updating = false; this.books[this.updateIndex] = this.book; this.book = { title: '', year: '', author: '', read: false } },
onUpdate now resets the updating flag, mutates the array to update the book and then empties the book model.
Deleting
This is the simplest; we utilize the array splice method to remove an item from the array based on there index:
onDelete(index) { // Remove one item starting at // the specified index this.books.splice(index, 1) }
Going Realtime with deepstream
We have just built a working app, but that was not the goal. We need to let all connected clients know when a record is added, updated and deleted by updating the table holding these records. This is where deepstream steps in to help out. At the moment, if we try such, other connected clients stays dumb:
deepstream Clients, Records & Lists
In the beginning of this post, we setup a deepstream server and left it running. In fact, the server is running on localhost at a given port, 6020. This server is just idle hoping for a client to connect and start exchanging data.
A deepstream client can come in any form, ranging from web, desktop, mobile and to even IoT. Our concern is Web for today, so we need to use deepstream's JS SDK to connect to the listening server. You can install the SDK by running:
npm install --save deepstream.io-client-js
Records in deepstream are like records in any other form of representing data. It is a single entity and store a given information item. The only difference is that deepstream records are live which means that data stored on records can be subscribed to by clients and the clients will be notified with payload at the slightest change.
Lists, on the other hand, help group records so they can be treated like a collection. Lists are as well live so they can be subscribed to for realtime changes and updates. We will utilize these deepstream features in our app to make the app realtime.
Authentication
Authentication just like in every other situation allows you to confirm that a user is actually who she claims to be. Your regular HTTP authentication differ a little from the how deepstream will handle authentication. However, the good thing is, it is easy to hook them together.
For every deepstream connecting client, an authentication is required. This does not necessarily mean that a credential must be provided; performing a login can just be anonymous and that applies to our case at the moment.
import * as ds from 'deepstream.io-client-js'; export default { name: 'app', data () { return { ds: ds('localhost:6020'), books$$: null // . . . } }, created () { this.ds.login({}, () => { console.log('logged in'); }); }, methods: {/* . . .*/} }
First we import the installed client, then we create a member variable ds to hold a reference to the deepstream while passing in the server's URL.
The created function is a lifecycle method which is called by Vue when the component is ready. This makes created a good candidate to handle deepstreawm authentication. Authentication is performed by calling deepstream.login method which receives a credential and a callback.
The books$$ property will keep a reference to the deepstream list we are yet to create.
We will revisit the CRUD process and update them with respect to deepstream but before that, we need to make all the connected clients listen to value changes so they can update accordingly
List and Records Subscriptions
created () { this.ds.login({}, () => { console.log('logged in'); }); this.books$$ = this.ds.record.getList('books'); /* * Entry added */ this.books$$.on('entry-added', (recordName, index) => { this.ds.record.getRecord(recordName).whenReady(record => { // The scond paramaeter, // a boolean, is a flag to specify whether // the callback should be invoked immediatly // with the current value record.subscribe(data => { if(!data.id) { if(data.title) { data.id = record.name; this.books.push(data); } } else { this.books = this.books.map(b => { if(data.id == b.id) { b = data; } console.log(b) return b; }); } }, true) }); }); /* * Entry removed */ this.books$$.on('entry-removed', (recordName, index) => { this.ds.record.getRecord(recordName).whenReady(record => { record.subscribe(data => { this.books.splice(this.books.indexOf(data, 1)); }, true) }); }); },
Lists and records API live on the record object. To create or retrieve an existing list, we use the getList method passing in, a name of our choice.
entry-added event listens to record addition to the created list. So when a record is added to the list, the event is triggered.
When a record is added, whenReady ensures the record is ready before we subscribe to it using the subscribe method.
subscribe takes a callback which checks if the data exists and updates it. If the record's data does not exist, it updates the record with the incoming data while setting the data's id to the record name (id). The books array is updated as data comes in.
entry-removed is the opposite of what we saw. It listens for when we remove a record so as to remove the record's data from the books array.
Creating
The onSubmit method will have to take a new shape. We won't be pushing data to books directly because that's already being done by the subscription. We just need to call a method that creates a record with data and adds the record to the list we created:
onSubmit() { const recordName = this.book.id || 'book/' + this.ds.getUid(); this.ds.record.has(recordName, (err, has) => { if(has){ this.onUpdate(); return; } else { const bookRecord = this.ds.record.getRecord(recordName); bookRecord.set(this.book); this.books$$.addEntry(recordName) this.book = { title: '', year: '', author: '', read: false } } }) },
We create/get a record using a UUID or the Id attached to data if data exists. The had method is used to check if the record exists or not. If it exists, we call the onUpdate method, else, we set the record to the new book and update the books$$ list with addEntry.
Updating
onUpdate() { const recordName = this.books[this.updateIndex].id; const bookRecord = this.ds.record.getRecord(recordName); bookRecord.set(this.book); this.book = { title: '', year: '', author: '', read: false } this.updating = false; }
onSubmit delegates updating to the onUpdate if the record name in question exists.
onUpdate retrieves the record name from the books array using the updateIndex. We get the record that the record name belongs to and the update the record with the book changes. No need to do anything on the list, it will behave accordingly.
Deleting
The onDelete method just calls removeEntry from the list to remove a record:
onDelete(index) { this.books$$.removeEntry(this.books[index].id); }
Conclusion
Building realtime apps keeps getting better with advent of more advanced solutions. You can as well perform HTTP auth or JWT auth as well as connect your database to deepstream when you need to persist data.
It's fascinating how we could build better UI apps using two simple to integrate platforms, Vue and deepstream. Vue is not just the only kid welcomed to the party. You can integrate deepstream with any other UI library out there using the same strategy of initialization and authentication.
via Scotch.io http://ift.tt/2lr7SdO
0 notes