The post How to Create Your Own Quiz appeared first on Tutsnare.
]]>Creating a quiz that not only tests knowledge but also engages the audience requires careful planning and creativity. Here are some tips to help you design quizzes that will captivate and challenge your participants:
By following these tips, you can create quizzes that are not only educational but also enjoyable, ensuring that your audience remains engaged and motivated to learn.
Creating your own quiz offers many advantages. For teachers, quizzes are an excellent tool for assessing student understanding and reinforcing key concepts. Content creators can use quizzes to engage their audience and increase interaction on their platforms. In addition, quizzes can be a fun way to challenge friends or test your knowledge on a particular topic. By designing your quiz, you have complete control over the content, difficulty level and format, ensuring that it is perfectly aligned with your goals.
Here are the key steps to creating your own quiz:
Here’s a comparison of popular platforms that can help you create and publish quizzes:
Feature | Platform A | Platform B | Platform C |
Ease of Use | User-friendly, drag-and-drop interface | Moderate learning curve | Simple, basic features |
Customization Options | Highly customizable with templates | Limited customization options | Basic customization available |
Analytics and Reporting | Advanced reporting features | Basic analytics | Limited reporting capabilities |
Integration with Other Tools | Seamless integration with LMS and social media | Limited integration options | No integration available |
Cost | Premium pricing, free trial available | Moderate pricing, educational discounts | Free, with paid upgrades |
Q1: What is the best platform for creating quizzes?
A1: The best platform depends on your specific needs. If you’re looking for advanced customization and reporting features, consider Platform A. For basic quizzes, Platform C is a great free option.
Q2: Can I create quizzes for free?
A2: Yes, many platforms offer free versions with basic features. However, for more advanced options, you may need to upgrade to a paid plan.
Q3: How do I share my quiz with others?
A3: Most quiz creation platforms allow you to share your quiz via a link or embed it directly into your website or social media channels.
Q4: Where can I find an AI tool to help create my own quiz?
A4: If you’re looking for an AI tool that specializes in creating quizzes, consider using hearify. This platform offers advanced features tailored to helping you create your own quiz with ease.
The post How to Create Your Own Quiz appeared first on Tutsnare.
]]>The post How to create forms in yii 2 appeared first on Tutsnare.
]]>‘yii\widgets\ActiveForm’
and ‘yii\helpers\Htm’
together to create forms.The former class is used to create a form and the later one is to render various form elements like textboxes,radio buttons,checkboxes etc. In this article we will explore how to create forms in yii 2 using activeform class.use yii\helpers\Html;
use yii\widgets\ActiveForm;
Now we have included the necessary classes, we have to create the form instance and begin the form using ActiveForm::begin()
method.In the same way we can close the form using ActiveForm::end()
. Note that we can instantiate the form with several attributes.This can be done by passing parameters to the ActiveForm::begin()
method.
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* default initialization */
$form = ActiveForm::begin();
/* parameterized initialization */
$form = ActiveForm::begin([
‘id’ => ‘form_id’,
‘options’ => [
‘class’ => ‘form_class’,
‘enctype’ => ‘multipart/form-data’,
],
]);
//render form elements here
ActiveForm::end();
Now for creating various form elements we will be requiring the Model object which we have passed to the view while rendering it.
A simple text input filed can be created as shown below example.
$form->field($model,'fieldName');
To customize the hint and label fields we can use the following code below.
$form->field($model,’fieldName’)->textInput()->hint(‘Hint Text’)->label(‘Label Name’);
Also the textInput()
class accepts an array as a parameter.You can set the various html attributes of the element such as class,maxlength,minlength in the parameter.Details can be found form the Yii2’s class reference.
Also we can use the following code to generate a text field as well.
$form->field($model,’fieldName’)->input(‘text);
In a similar manner we can create text areas as per the below code.
$form->field($model,'fieldName')->textarea();
$form->field($model,'fieldName')->textarea()->label('Label');
$form->field($model,'fieldName')->textarea(array('rows'=>2,'cols'=>5));
Password fields can be created using the following code:
//Format 1
$form->field($model, ‘fieldName’)->input(‘password’);
//Format 2
$form->field($model, ‘fieldName’)->passwordInput();
//Format 3
$form->field($model, ‘fieldName’)->passwordInput()->hint(‘Provide your hint here’)->label(‘Label’);
The following code generates a html email input field.
$form->field($model, 'fieldName')->input('email');
fileInput()
function is used to create a file input field
$form->field($model, 'fieldName')->fileInput();
To create a multiupload field use ‘multiple’ parameter in fileInput()
method.Please refer the code below for this.
$form->field($model, 'fieldName[]')->fileInput(['multiple'=>'multiple']);
Checkbox button Field:
$form->field($model, 'fieldName')->checkbox();
We can customize the label and other attributes by passing an array as an attribute to the checkbox()
function.
$form->field($model, 'fieldName')->checkbox(array(
'label'=>'',
'labelOptions'=>array('style'=>'padding:5px;'),
'disabled'=>true
))
->label('Label');
Using checkboxList()
method and passing an array as the argument to it we can create a checkbox list.The array will be rendered as the options for the checkbox list.
$form->field($model, 'fieldName[]')->checkboxList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']);;
Much similar to the checkbox field we can create a radio button field as shown below:
//wihout any parameters
$form->field($model, 'fieldName')->radio();
//with parameter
$form->field($model, 'fieldName')->radio(array(
'label'=>'',
'labelOptions'=>array('style'=>'padding:5px;'),
'disabled'=>true
))
->label('Label');
Using radioList()
method we can create a radio button list, similarly we have created for the checkbox list.
$form->field($model, 'fieldName[]')->radioList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']);
dropDownList()
function is used to create HTML ‘select’ tag input field.The options are passed as an array as an arguments.
$form->field($model, 'fieldName')->dropDownList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']);
To create a hidden input field we use hidden Input method.
$form->hiddenInput($model,'fieldName',array('value'=>value'));
Finally the form submit button can be created using Html::submitButton()
method.
Html::submitButton(‘Submit’, [‘class’=> ‘btn btn-primary’]);
The post How to create forms in yii 2 appeared first on Tutsnare.
]]>The post How to use session in laravel appeared first on Tutsnare.
]]>
syntax :- Session::put('key', 'value');
example :- Session::put('email', $data['email']); //array index
Session::put('email', $email); // a single variable
Session::put('email', 'sharmarakesh395@gmail.com'); // a string
Retrieving value from session :-
syntax :- Session::get('key');
example :- Session::get('email');
Checking a variable exist in session :-
// Checking email key exist in session.
if (Session::has('email')) {
echo Session::get('email');
}
Deleting a variable from session :-
syntax :- Session::forget('key');
example :- Session::forget('email');
Removing all variables from session :-
Session::flush();
Working with array values :-
Setting an array in session :-
$data = Array ( [_token] => P1VsHQZQdpguhWN82n9znnfuvG2aAf7fCk8SJtUV [email] => demo1006@gmail.com [password] => 123456 )
Session::push('user', $data); //$data is an array and user is a session key.
Getting an array item from session :-
//array in session looks like
Array (
[0] => Array
(
[_token] => P1VsHQZQdpguhWN82n9znnfuvG2aAf7fCk8SJtUV
[email] => demo1006@gmail.com
[password] => 123456
)
)
//check and getting above array
if (Session::has('user')) {
$user = Session::get('user');
echo $user[0]['email'];
}
pushing an index in existing array in session :-
Session::push('user.mytoken', 'rakesh');
//will be pushed in user array with new index "mytoken" like:-
Array
(
[0] => Array
(
[_token] => P1VsHQZQdpguhWN82n9znnfuvG2aAf7fCk8SJtUV
[email] => demo1006@gmail.com
[password] => 123456
)
[mytoken] => Array
(
[0] => rakesh
)
)
The post How to use session in laravel appeared first on Tutsnare.
]]>The post The main features and components of Laravel appeared first on Tutsnare.
]]>Artisan is a console utility built into Laravel that provides many useful commands for working with the framework. Artisan helps automate many routine tasks such as generating controllers, models, migrations, tests, etc. In addition, Artisan provides the ability to create custom commands, which allows you to automate any project-specific operations.
Eloquent is an ORM (Object-Relational Mapping) included in Laravel. It provides a simple and intuitive way to interact with a database using an object-oriented approach. With Eloquent, you can easily perform CRUD operations (create, read, update, delete), as well as interact with relationships between tables (one-to-one, one-to-many, many-to-many, etc.).
Fluent is a universal query builder that allows you to create and execute database queries in PHP without using SQL. Fluent supports most types of queries, including select, insert, update, and delete records, as well as data aggregation.
Blade provides a convenient and intuitive way to create and embed templates in Laravel applications. It supports template inheritance, sections, connecting sub-templates, loops, conditional statements, and many other features.
Validation Laravel offers excellent tools for data validation. You can use both simple validation rules (required field, minimum/maximum length, uniqueness, etc.) and create your own rules.
Laravel offers tools for controlling database versions using migrations. Migrations allow you to track changes in the database structure and apply these changes to other servers (test, production) in an automatic mode.
Laravel provides built-in support for testing using the PHPUnit library. Thanks to this, developers can write tests for their application, make sure it works correctly, and prevent errors in the future.
Laravel includes convenient tools for user authentication. The framework provides a simple and flexible API for working with authentication, which makes it easy to implement various scenarios (login, registration, password recovery, etc.).
Comparing all the above-mentioned components of Laravel, we can conclude that it is adaptable and versatile. Laravel allows you to create websites of almost any complexity, providing the developer with the most convenient and well-thought-out tools.
The post The main features and components of Laravel appeared first on Tutsnare.
]]>The post Who is an online store on WordPress / WooCommerce suitable for? appeared first on Tutsnare.
]]>An entrepreneur can have a large-scale offline business, but not know anything about online commerce. It is for such cases that WooCommerce exists – a plugin that turns a regular WordPress site into a full-fledged online store. Test-driving a commercial WordPress site is justified for two reasons: quick launch – one, and budget – two. Choose a ready-made design template, customize the basic functionality, get your first customers, and feel the atmosphere of online commerce with WooCommerce.
A WordPress store is an ideal option for business beginners. When things are just getting started and your business hasn’t gained much momentum, a WooCommerce website will be a great solution. A free theme and a set of plugins necessary for safe and convenient online shopping are more than enough. As soon as your business meets your expectations online and embarks on a steady growth path, rest assured that WooCommerce will grow with you. Connect marketing tools, improve commercial solutions, and scale your online store as your brand grows in popularity.
A WooCommerce website is relevant primarily for small and medium-sized online stores. Otherwise, due to the heavy load on the server, the work of the WordPress CMS slows down, which inevitably leads to an increase in the price of hosting. When the catalog contains up to 1-2 thousand products, it is an ideal option for developing an online store on WordPress/WooCommerce.
WordPress in conjunction with WooCommerce allows you to launch an online store in a matter of hours and start selling online as soon as possible. And with the help of a developer, you are guaranteed not only fast but also high-quality results. Customizing a template, creating a catalog, integrating with CRM, connecting payments and delivery systems – all these functions are available out of the box, and you just need to configure them correctly. WooCommerce is a great solution for those who cannot and do not want to wait.
The post Who is an online store on WordPress / WooCommerce suitable for? appeared first on Tutsnare.
]]>The post Is PHP suitable for beginners appeared first on Tutsnare.
]]>Thanks to such popularity, a beginner doesn’t even need to write code, as examples of it can always be found on the Internet. Thus, a beginner is unlikely to encounter a problem that cannot be solved.
In addition, PHP has a large non-corporate application sector that can be easily entered by a beginner even with minimal knowledge, as well as a significant freelance market. PHP is one of the easiest programming languages to learn and is well suited for beginners with basic knowledge of computer networks and programming.
PHP is used in many areas of development today.
Web development. Originally developed for creating web pages, PHP allows you to create websites with intuitive and responsive design quickly and easily. PHP’s functionality, such as integration with HTML, good compatibility with various databases, security, and user-friendly interface, contributes to the convenience of web development.
In today’s ecosystem, every web page requires a high level of customization and should provide a highly interactive user interface. Since PHP scripts run on the server, a page with HTML code can be created in a dynamic manner. And site visitors deal with customized pages without encountering scripts.
E-commerce. This is another big area where PHP offers many easy ways to create products. Many popular online platforms such as OpenCart, Zen Cart, Magento, PrestaShop, and Ubercart are made with PHP.
Enterprise software. Enterprise software includes content management systems (CMS), customer relationship management systems (CRM), resource management systems (ERP), and other tools for managing enterprise assets. The use of PHP for enterprise software development is gaining momentum due to its flexibility, easy integration, and various payment options.
Database development. Writing a database in PHP is greatly simplified by using special extensions or connecting to one of the databases that support the ODBC standard. PHP provides support for various databases, including MySQL, Oracle and MS Access (more than 20 in total), and can also be used to prepare unique databases. PHP is characterized by the simplicity of generating a page that works with the database.
Mobile applications. Today, you can see few self-sufficient applications, most of them rely on backend services. The server part of the application is responsible for combining various data from the mobile device, user behavior patterns, saving user settings, etc. Several PHP frameworks, such as Symfony and Laravel, are well suited for building the backend of mobile apps.
Given the ease of learning PHP, open source software, wide scope, and a large number of websites written in PHP, this language can be considered a good option for starting in IT.
The post Is PHP suitable for beginners appeared first on Tutsnare.
]]>The post How to install laravel on windows xampp appeared first on Tutsnare.
]]>Now time of frameworks in php like laravel, codeigniter etc and easy to install php frameworks on local server like xampp, wamp etc. Below we will see installation steps of a php framework laravel on windows xampp. Let’s see how to install laravel on windows xmapp. for this we need some server requirements, some of software installation.
Below are the steps of How to install laravel on windows xampp using composer:-
Server requirement:-
PHP >= 5.4
MCrypt PHP Extension
Installation steps :-
1. Laravel requires Composer to manage its dependencies. so first need to download composer.
A. After download composer, install composer on your system using below options:-
a. Shell menus:- Run composer from Windows Explorer by right clicking folder items.(optional)
b. next step require php.exe
which is normally in xampp/htdocs/php
folder. and continue with more instructions and click next to finish installation.
2. Installation process also requires Git to be installed on the server to successfully complete the installation.
If you not have GIT installed on your system:-
a. Download Git and install it.
3. Now download latest version of laravel and unzip into your local server.
For example you have put into your local server where the directory is D:\xampp\htdocs\laravel\
.
Using Shell menus (works if you already selected shell menus option on installation of composer) :-
1. Right click on your laravel folder and click on Use Composer here
.
2. will open CMD and enter command composer install
and press enter key.
3. Now wait until process completed. it will take few time to download in your computer.
Using CMD with direct download :-
1. Open the CMD (start>serch for “cmd”> click on cmd.exe)in your computer and change the directory according to your laravel directory.(ex:- D:\xampp\htdocs\laravel>)
2. enter command composer install
and press enter key.(ex:- D:\xampp\htdocs\laravel>composer install)
3. Now wait until process completed. it will take few time to download in your computer.
Using CMD create project command :-
1. Open the CMD (start>serch for “cmd”> click on cmd.exe)in your computer and run below command. “–prefer-dist” will be preferred location where you want to install laravel.# install laravel using create project command composer create-project laravel/laravel –prefer-dist #composer create-project laravel/laravel d:\xampp\htdocs\laranew
2. Now wait until process completed. and you done.
After successfully installed you can access http://localhost/laravel/public/
Now you have finished installation steps of laravel using composer.
The post How to install laravel on windows xampp appeared first on Tutsnare.
]]>The post Upload files in laravel 5 appeared first on Tutsnare.
]]>It’s easy to working with files or images in laravel 5. we can easily validate and upload files in laravel 5. laravel 5 have it’s own functions to make files upload easy and fast. i am sharing some code to upload image in laravel 5 or any of files type. it’s also easy to validate file types.
1. create a form with attribute ‘files’=>true or try below code (in my case i have resources/views/pages/upload.blade.php) :-
<div class="about-section">
<div class="text-content">
<div class="span7 offset1">
@if(Session::has('success'))
<div class="alert-box success">
<h2>{!! Session::get('success') !!}</h2>
</div>
@endif
<div class="secure">Upload form</div>
{!! Form::open(array('url'=>'apply/upload','method'=>'POST', 'files'=>true)) !!}
<div class="control-group">
<div class="controls">
{!! Form::file('image') !!}
<p class="errors">{!!$errors->first('image')!!}</p>
@if(Session::has('error'))
<p class="errors">{!! Session::get('error') !!}</p>
@endif
</div>
</div>
<div id="success"> </div>
{!! Form::submit('Submit', array('class'=>'send-btn')) !!}
{!! Form::close() !!}
</div>
</div>
</div>
2. create a controller and add below function (in my case i have ApplyController):-
<?php namespace App\Http\Controllers;
use Input;
use Validator;
use Redirect;
use Request;
use Session;
class ApplyController extends Controller {
public function upload() {
// getting all of the post data
$file = array('image' => Input::file('image'));
// setting up rules
$rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
// send back to the page with the input data and errors
return Redirect::to('upload')->withInput()->withErrors($validator);
}
else {
// checking file is valid.
if (Input::file('image')->isValid()) {
$destinationPath = 'uploads'; // upload path
$extension = Input::file('image')->getClientOriginalExtension(); // getting image extension
$fileName = rand(11111,99999).'.'.$extension; // renameing image
Input::file('image')->move($destinationPath, $fileName); // uploading file to given path
// sending back with message
Session::flash('success', 'Upload successfully');
return Redirect::to('upload');
}
else {
// sending back with error message.
Session::flash('error', 'uploaded file is not valid');
return Redirect::to('upload');
}
}
}
}
3. setting up routes :-
Route::get('upload', function() {
return View::make('pages.upload');
});
Route::post('apply/upload', 'ApplyController@upload');
Now you are all set with upload an image in laravel 5 or upload files in laravel 5. also sharing below some of description or method to use in files upload to validate or getting information of files which makes easy to working with files in laravel
$file = Input::file('image');
if (Input::hasFile('image')) { }
if (Input::file('image')->isValid()) { }
$destinationPath = ‘your path to upload file’ and $fileName= ‘giving a new name to file’
Input::file('image')->move($destinationPath);
Input::file('image')->move($destinationPath, $fileName);
$path = Input::file('image')->getRealPath();
$name = Input::file('image')->getClientOriginalName();
$extension = Input::file('image')->getClientOriginalExtension();
$size = Input::file('image')->getSize();
$mime = Input::file('image')->getMimeType();
The post Upload files in laravel 5 appeared first on Tutsnare.
]]>The post Post data using ajax in laravel 5 appeared first on Tutsnare.
]]>If you are going to work with ajax data post to controller or route in laravel 5. There are some need to get ajax call work correctly. Your requirement is csrf token. A default feature in Laravel is it’s automatic CSRF security. When you working with forms it’s automatically add a “_token” hidden field to your form. On each post request token will be matched for csrf protection. so it’s one more cool feature provided by laravel 5.
If you are using default way for ajax data post, you will get “500 internal server error” in laravel 5. cause you missing csrf token posting with ajax post data. and error reason is token not being matched on post request. so every time a form data is posting require csrf token match. else you will get “500 internal server error” in laravel.
In this article we will explore how to solve 500 internal server error in ajax post or call in laravel or how to Post data using ajax in laravel 5. there are many ways to do this but i am sharing two ways :-
1. Adding on each request
2. globally
In this way we need to add token on each ajax call with data which is posting
view :- add a “login.blade.php” under “resources/views/” and add below code to make a form
<div class="secure">Secure Login form</div>
{!! Form::open(array('url'=>'account/login','method'=>'POST', 'id'=>'myform')) !!}
<div class="control-group">
<div class="controls">
{!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Email')) !!}
</div>
</div>
<div class="control-group">
<div class="controls">
{!! Form::password('password',array('class'=>'form-control span6', 'placeholder' => 'Please Enter your Password')) !!}
</div>
</div>
{!! Form::button('Login', array('class'=>'send-btn')) !!}
{!! Form::close() !!}
Now add your ajax call or post data script to your layout footer or in the same file.
<script type="text/javascript">
$(document).ready(function(){
$('.send-btn').click(function(){
$.ajax({
url: 'login',
type: "post",
data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val()},
success: function(data){
alert(data);
}
});
});
});
</script>
Routes :- Add your get and post route to “app/Http/routes.php”
Route::get('account/login', function() {
return View::make('login');
});
Route::post('account/login', 'AccountController@login');
Controller :- add a controller to “app/Http/Controllers” with named “AccountController.php” and add below code
<?php namespace App\Http\Controllers;
use Input;
use Request;
class AccountController extends Controller {
public function login() {
// Getting all post data
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
}
After all make go to your page url and click on button and you get your data has been posted and you will get alert with success.
In this way we will add token for globally work with ajax call or post. so no need to send it with data post.
1. Add a meta tag to your layout header :- csrf_token() will be the same as “_token” CSRF token that Laravel automatically adds in the hidden input on every form.
<meta name="_token" content="{!! csrf_token() !!}"/>
2. Now add below code to footer of your layout, or where it will set for globally or whole site pages. this will pass token to each ajax request.
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
Now make an ajax post request an you are done your data will post successfully.
The post Post data using ajax in laravel 5 appeared first on Tutsnare.
]]>The post Send csrf token using angularjs in laravel appeared first on Tutsnare.
]]>For this we need to define a constant then get value of csrf constant and send via http post
1. define angularjs app :-
var app = angular.module('myValidateApp', []);
2. define constant :-
app.constant("CSRF_TOKEN", '{!! csrf_token() !!}');
3. send via http post :-
app.controller('validateCtrl', function($scope, $http, CSRF_TOKEN) {
$scope.submitForm = function(isValid) {
// check all goes fine?
if (isValid) {
var data = {'_token':CSRF_TOKEN};
$http({
method: 'POST',
url: 'YOUR_POST_URL',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
data: $.param(data)
}).
success(function(data, status, headers, config) {
alert(data);
});
}
};
});
Below we will see an example of form that posting form data with csrf token using angularjs in laravel. so let’s create a angularjs and html form.
view:- create a “angpost.blade.php” under “resources/views/” and add below code
<form ng-app="myValidateApp" ng-controller="validateCtrl" name="myTestForm" ng-submit="submitForm(myTestForm.$valid)" novalidate>
<p>Username:<br />
<input type="text" name="username" ng-model="username" ng-model-options="{ updateOn: 'blur' }" required><br />
<span style="color:red" ng-show="myTestForm.username.$dirty && myTestForm.username.$invalid">
<span ng-show="myTestForm.username.$error.required">Username is required.</span>
</span>
</p>
<p>Phone:<br />
<input type="text" name="phone" ng-model="phone" ng-minlength="10" ng-model-options="{ updateOn: 'blur' }" ng-pattern="/^[0-9]+$/" required><br />
<span style="color:red" ng-show="myTestForm.phone.$dirty && myTestForm.phone.$invalid">
<span ng-show="myTestForm.phone.$error.required">Phone is required.</span>
<span ng-show="myTestForm.phone.$error.pattern">Phone must be numeric.</span>
<span ng-show="myTestForm.phone.$error.minlength">Phone must be min 10 char.</span>
</span>
</p>
<p>Email:<br />
<input type="email" name="email" ng-model="email" ng-model-options="{ updateOn: 'blur' }" required><br />
<span style="color:red" ng-show="myTestForm.email.$dirty && myTestForm.email.$invalid">
<span ng-show="myTestForm.email.$error.required">Email is required.</span>
<span ng-show="myTestForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit" value="Submit" ng-disabled="myTestForm.phone.$dirty && myTestForm.phone.$invalid || myTestForm.username.$dirty && myTestForm.username.$invalid || myTestForm.email.$dirty && myTestForm.email.$invalid">
</p>
</form>
controller :- create a “AngcsrfController.php” under “app/Http/Controllers” and add below code
<?php namespace App\Http\Controllers;
use Input;
use Validator;
use Redirect;
use Session;
class AngcsrfController extends Controller {
public function angpost() {
// Getting all post data
if(Session::token() == Input::get('_token')){
$data = Input::all();
print_r($data);die;
}
}
}
Adding angularjs script :- include angularjs library file in your header or in the same view file.
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
Now add the angularjs post script code in the same view file or footer
<script>
var app = angular.module('myValidateApp', []);
//Define csrf token as a constant.
app.constant("CSRF_TOKEN", '{!! csrf_token() !!}');
// pass token to controller function.
app.controller('validateCtrl', function($scope, $http, CSRF_TOKEN) {
$scope.submitForm = function(isValid) {
// check all goes fine?
if (isValid) {
var data = { 'username': $scope.username, 'email': $scope.email, 'phone': $scope.phone, '_token':CSRF_TOKEN};
$http({
method: 'POST',
url: 'angcsrf/angpost',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
data: $.param(data)
}).
success(function(data, status, headers, config) {
alert(data);
});
}
};
});
</script>
Routes :- add below code in your “app/Http/routes.php”
Route::get('angpost', function() {
return View::make('angpost');
});
Route::post('angcsrf/angpost', 'AngcsrfController@angpost');
After set all code run the url “yoursite/angpost” and fill the form and click on submit you will get a alert with success posted data with csrf token match. co you are done with send csrf token using angularjs in laravel and how to post form data using angularjs in laravel.
The post Send csrf token using angularjs in laravel appeared first on Tutsnare.
]]>