Tutsnare https://tutsnare.com/ PHP, Wordpress and Laravel web development courses Tue, 20 Aug 2024 12:11:45 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://tutsnare.com/wp-content/uploads/2023/11/cropped-code-6127616_640-32x32.png Tutsnare https://tutsnare.com/ 32 32 How to Create Your Own Quiz https://tutsnare.com/how-to-create-your-own-quiz/ Tue, 20 Aug 2024 12:11:45 +0000 https://tutsnare.com/?p=330 Quizzes are a fun and interactive way to test knowledge, engage your audience and reinforce learning. Whether you are an educator, content creator, or simply someone who enjoys sharing trivia, creating your own quiz can be a rewarding experience. In […]

The post How to Create Your Own Quiz appeared first on Tutsnare.

]]>
Quizzes are a fun and interactive way to test knowledge, engage your audience and reinforce learning. Whether you are an educator, content creator, or simply someone who enjoys sharing trivia, creating your own quiz can be a rewarding experience. In this article https://www.customwritings.com/blog/words-to-describe-a-student-academically.html we will guide you through the steps of designing and creating your quiz, from planning the questions to sharing the final product with others.

Tips for Creating Engaging Quizzes

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:

  • Know your audience: Tailor the questions to the interests and knowledge level of your audience. This ensures that the quiz is neither too easy nor too difficult, maintaining engagement throughout.
  • Use a variety of question types: Mix question formats by including multiple-choice, true/false, and short answer questions. This variety makes the quiz interesting and tests different types of knowledge.
  • Incorporate images: Adding images, videos or graphics can make the quiz more interactive and visually appealing, helping to keep participants engaged.
  • Keep it concise: Although it is important to cover the topic in depth, avoid making the quiz too long. A concise quiz is more likely to grab the audience’s attention and encourage completion.
  • Provide immediate feedback: Offering immediate feedback on answers can enhance the learning experience and make the quiz more rewarding for 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.

Why Create Your Own Quiz?

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.

Steps to Create Your Own Quiz

Here are the key steps to creating your own quiz:

  • Define the purpose: Determine why you are creating the quiz. Is it for educational, entertainment, or engagement purposes?
  • Choose a topic: Select a topic that interests you or is relevant to your audience.
  • Design questions: Create a variety of question types, such as multiple choice, true/false, and short answer.
  • Set the level of difficulty: Decide whether the quiz will be easy, moderate or challenging based on your target audience.
  • Select a platform: Choose an online tool or software to create and publish the quiz.
  • Test the quiz: Before sharing it with others, take the quiz yourself to make sure everything works as expected.
  • Share and monitor: Publish your quiz and track its progress. Use the feedback to improve future quizzes.

Comparison of Quiz Creation Platforms

Here’s a comparison of popular platforms that can help you create and publish quizzes:

FeaturePlatform APlatform BPlatform C
Ease of UseUser-friendly, drag-and-drop interfaceModerate learning curveSimple, basic features
Customization OptionsHighly customizable with templatesLimited customization optionsBasic customization available
Analytics and ReportingAdvanced reporting featuresBasic analyticsLimited reporting capabilities
Integration with Other ToolsSeamless integration with LMS and social mediaLimited integration optionsNo integration available
CostPremium pricing, free trial availableModerate pricing, educational discountsFree, with paid upgrades

FAQs

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.

]]>
How to create forms in yii 2 https://tutsnare.com/how-to-create-forms-in-yii-2/ Mon, 25 Mar 2024 10:22:54 +0000 https://tutsnare.com/?p=305 In Yii2 we use the ‘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 […]

The post How to create forms in yii 2 appeared first on Tutsnare.

]]>
In Yii2 we use the ‘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.
First we need include the above two classes in our view file.

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.

Creating Text inputs:

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);

Creating Textarea fields:

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));

Creating password fields:

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’);

Email Input Field:

The following code generates a html email input field.

$form->field($model, 'fieldName')->input('email');

File Upload Field:

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');

Checkbox List Input Field:

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']);;

Radio button Field:

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');

Radio button list Field:

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']);

DropDown List Field:

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']);

Hidden input Field:

To create a hidden input field we use hidden Input method.

$form->hiddenInput($model,'fieldName',array('value'=>value'));

Hidden input Field:

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.

]]>
How to use session in laravel https://tutsnare.com/how-to-use-session-in-laravel/ Thu, 21 Mar 2024 15:16:31 +0000 https://tutsnare.com/?p=167 Laravel provides more inbuilt method to get and set session data. it’s easy to working with session in laravel.

The post How to use session in laravel appeared first on Tutsnare.

]]>
Laravel provides more inbuilt method to get and set session data. it’s easy to working with session in laravel. A session variable is used to store some information or some data about user or anything you want to access on all pages of an application.In laravel session configuration is stored in “app/config/session.php”.
so let’s see how to use session in laravel.
Setting a single variable in session :-


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 main features and components of Laravel https://tutsnare.com/the-main-features-and-components-of-laravel/ Mon, 04 Dec 2023 07:57:41 +0000 https://tutsnare.com/?p=118 Laravel offers many flexible tools and components for writing code that greatly simplify the development and maintenance of web applications.

The post The main features and components of Laravel appeared first on Tutsnare.

]]>
Laravel offers many flexible tools and components for writing code that greatly simplify the development and maintenance of web applications.

Artisan console

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 ORM

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 designer

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 templating engine

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

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.

Database version control system

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.

Unit testing

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.

Authentication

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.

]]>
Who is an online store on WordPress / WooCommerce suitable for? https://tutsnare.com/who-is-an-online-store-on-wordpress-woocommerce-suitable-for/ Fri, 07 Apr 2023 07:57:00 +0000 https://tutsnare.com/?p=121 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.

The post Who is an online store on WordPress / WooCommerce suitable for? appeared first on Tutsnare.

]]>
For entrepreneurs testing online business

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.

For people who are just starting their way in online trading

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.

For store owners with a small assortment of products

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.

For entrepreneurs who need to develop a website quickly

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.

]]>
Is PHP suitable for beginners https://tutsnare.com/is-php-suitable-for-beginners/ Wed, 21 Jul 2021 07:48:00 +0000 https://tutsnare.com/?p=115 Despite the fact that the global IT community has long predicted a decline in PHP, today about 80% of all websites use it as a server language.

The post Is PHP suitable for beginners appeared first on Tutsnare.

]]>
Despite the fact that the global IT community has long predicted a decline in PHP, today about 80% of all websites use it as a server language. Out of 10 thousand of the world’s busiest websites, 56% choose PHP.

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.

]]>
How to install laravel on windows xampp https://tutsnare.com/how-to-install-laravel-on-windows-xampp/ Sun, 15 Nov 2020 13:51:29 +0000 https://tutsnare.com/?p=104 How to install laravel on windows xampp :- 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 […]

The post How to install laravel on windows xampp appeared first on Tutsnare.

]]>
How to install laravel on windows xampp :-

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)

cm1

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.

How to install laravel on windows xampp

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)

cm3

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

laravel_win3

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.

laravel_win3

The post How to install laravel on windows xampp appeared first on Tutsnare.

]]>
Upload files in laravel 5 https://tutsnare.com/upload-files-in-laravel/ Sun, 15 Nov 2020 12:19:16 +0000 https://tutsnare.com/?p=39 Upload files or images in laravel 5:- 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 […]

The post Upload files in laravel 5 appeared first on Tutsnare.

]]>
Upload files or images in laravel 5:-

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');
upload form

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

Getting uploaded file :-


$file = Input::file('image');

Check file was uploaded :-


if (Input::hasFile('image')) { }

Check uploaded file is valid :-


if (Input::file('image')->isValid()) { }

Moving uploaded file :-

$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);

Getting path of uploaded file :-


$path = Input::file('image')->getRealPath();

Getting original name of uploaded file :-


$name = Input::file('image')->getClientOriginalName();

Getting extension Of uploaded file :-


$extension = Input::file('image')->getClientOriginalExtension();

Getting size of An uploaded file :-


$size = Input::file('image')->getSize();

Getting MIME Type of uploaded file :-


$mime = Input::file('image')->getMimeType();

The post Upload files in laravel 5 appeared first on Tutsnare.

]]>
Post data using ajax in laravel 5 https://tutsnare.com/post-data-using-ajax-in-laravel-5/ Tue, 18 Jul 2017 15:08:00 +0000 https://tutsnare.com/?p=164 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.

The post Post data using ajax in laravel 5 appeared first on Tutsnare.

]]>
Post data using ajax in laravel 5 to controller

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.

Why on ajax post 500 internal server error laravel :-

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.

Post data using ajax in laravel 5

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

How to Post data using ajax in laravel 5 :-

1. Adding on each request and post data to controller :-

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.

2. globally way :-

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.

]]>
Send csrf token using angularjs in laravel https://tutsnare.com/send-csrf-token-using-angularjs-in-laravel/ Tue, 18 Jul 2017 10:27:00 +0000 https://tutsnare.com/?p=311 Sometimes we need to use angularjs in our form to validate or posting data in laravel. there is also need of csrf token match.

The post Send csrf token using angularjs in laravel appeared first on Tutsnare.

]]>
Sometimes we need to use angularjs in our form to validate or posting data in laravel. there is also need of csrf token match. if we are not using html class form::open() then csrf token will not be automatically added to our form. so we need to manually send csrf token using angularjs in laravel.

How to send csrf token using angularjs in laravel :-

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);
    });
  }
};
});

How to Post Form data using angularjs in laravel :-

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.

Send csrf token using angularjs in laravel

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.

]]>