10 security tips to protect your website from hackers


Source of this article is as here.

 

You may not think your site has anything worth being hacked for, but websites are compromised all the time. The majority of website security breaches are not to steal your data or deface your website, but instead attempts to use your server as an email relay for spam, or to setup a temporary web server, normally to serve files of an illegal nature.

Hacking is regularly performed by automated scripts written to scour the Internet in an attempt to exploit known website security issues in software. Here are our top 10 tips to help keep you and your site safe online.

01. Keep software up to date

It may seem obvious, but ensuring you keep all software up to date is vital in keeping your site secure. This applies to both the server operating system and any software you may be running on your website such as a CMS or forum. When website security holes are found in software, hackers are quick to attempt to abuse them.

If you are using a managed hosting solution then you don’t need to worry so much about applying security updates for the operating system as the hosting company should take care of this.

If you are using third-party software on your website such as a CMS or forum, you should ensure you are quick to apply any security patches. Most vendors have a mailing list or RSS feed detailing any website security issues. WordPress, Umbraco and many other CMSes notify you of available system updates when you log in.

02. SQL injection

SQL injection attacks are when an attacker uses a web form field or URL parameter to gain access to or manipulate your database. When you use standard Transact SQL it is easy to unknowingly insert rogue code into your query that could be used to change tables, get information and delete data. You can easily prevent this by always using parameterised queries, most web languages have this feature and it is easy to implement.

Consider this query:

"SELECT * FROM table WHERE column = '" + parameter + "';"

If an attacker changed the URL parameter to pass in ‘ or ‘1’=’1 this will cause the query to look like this:

"SELECT * FROM table WHERE column = '' OR '1'='1';"

Since ‘1’ is equal to ‘1’ this will allow the attacker to add an additional query to the end of the SQL statement which will also be executed.

03. XSS

Cross site scripting is when an attacker tries to pass in JavaScript or other scripting code into a web form to attempt to run malicious code for visitors of your site. When creating a form always ensure you check the data being submitted and encode or strip out any HTML.

04. Error messages

Be careful with how much information you give away in your error messages. For example if you have a login form on your website you should think about the language you use to communicate failure when attempting logins. You should use generic messages like “Incorrect username or password” as not to specify when a user got half of the query right. If an attacker tries a brute force attack to get a username and password and the error message gives away when one of the fields are correct then the attacker knows he has one of the fields and can concentrate on the other field.

Keep your error messages vague

05. Server side validation/form validation

Validation should always be done both on the browser and server side. The browser can catch simple failures like mandatory fields that are empty and when you enter text into a numbers only field. These can however be bypassed, and you should make sure you check for these validation and deeper validation server side as failing to do so could lead to malicious code or scripting code being inserted into the database or could cause undesirable results in your website.

06. Passwords

Everyone knows they should use complex passwords, but that doesn’t mean they always do. It is crucial to use strong passwords to your server and website admin area, but equally also important to insist on good password practices for your users to protect the security of their accounts.

As much as users may not like it, enforcing password requirements such as a minimum of around eight characters, including an uppercase letter and number will help to protect their information in the long run.

Passwords should always be stored as encrypted values, preferably using a one way hashing algorithm such as SHA. Using this method means when you are authenticating users you are only ever comparing encrypted values. For extra website security it is a good idea to salt the passwords, using a new salt per password.

In the event of someone hacking in and stealing your passwords, using hashed passwords could help damage limitation, as decrypting them is not possible. The best someone can do is a dictionary attack or brute force attack, essentially guessing every combination until it finds a match. When using salted passwords the process of cracking a large number of passwords is even slower as every guess has to be hashed separately for every salt + password which is computationally very expensive.

Thankfully, many CMSes provide user management out of the box with a lot of these website security features built in, although some configuration or extra modules might be required to use salted passwords (pre Drupal 7) or to set the minimum password strength. If you are using .NET then it’s worth using membership providers as they are very configurable, provide inbuilt website security and include readymade controls for login and password reset.

07. File uploads

Allowing users to upload files to your website can be a big website security risk, even if it’s simply to change their avatar. The risk is that any file uploaded however innocent it may look, could contain a script that when executed on your server completely opens up your website.

If you have a file upload form then you need to treat all files with great suspicion. If you are allowing users to upload images, you cannot rely on the file extension or the mime type to verify that the file is an image as these can easily be faked. Even opening the file and reading the header, or using functions to check the image size are not full proof. Most images formats allow storing a comment section which could contain PHP code that could be executed by the server.

So what can you do to prevent this? Ultimately you want to stop users from being able to execute any file they upload. By default web servers won’t attempt to execute files with image extensions, but it isn’t recommended to rely solely on checking the file extension as a file with the name image.jpg.php has been known to get through.

Some options are to rename the file on upload to ensure the correct file extension, or to change the file permissions, for example, chmod 0666 so it can’t be executed. If using *nix you could create a .htaccess file (see below) that will only allow access to set files preventing the double extension attack mentioned earlier.

deny from all
    <Files ~ "^\w+\.(gif|jpe?g|png)$">
    order deny,allow
    allow from all
    </Files>

Ultimately, the recommended solution is to prevent direct access to uploaded files all together. This way, any files uploaded to your website are stored in a folder outside of the webroot or in the database as a blob. If your files are not directly accessible you will need to create a script to fetch the files from the private folder (or an HTTP handler in .NET) and deliver them to the browser. Image tags support an src attribute that is not a direct URL to an image, so your src attribute can point to your file delivery script providing you set the correct content type in the HTTP header. For example:

<img src="/imageDelivery.php?id=1234" />
     
<?php
      // imageDelivery.php
     
      // Fetch image filename from database based on $_GET["id"]
      ...
     
      // Deliver image to browser
       Header('Content-Type: image/gif');
      readfile('images/'.$fileName);  
     
?>

Most hosting providers deal with the server configuration for you, but if you are hosting your website on your own server then there are few things you will want to check.

Ensure you have a firewall setup, and are blocking all non essential ports. If possible setting up a DMZ (Demilitarised Zone) only allowing access to port 80 and 443 from the outside world. Although this might not be possible if you don’t have access to your server from an internal network as you would need to open up ports to allow uploading files and to remotely log in to your server over SSH or RDP.

If you are allowing files to be uploaded from the Internet only use secure transport methods to your server such as SFTP or SSH.

If possible have your database running on a different server to that of your web server. Doing this means the database server cannot be accessed directly from the outside world, only your web server can access it, minimising the risk of your data being exposed.

Finally, don’t forget about restricting physical access to your server.

09.SSL

SSL is a protocol used to provide security over the Internet. It is a good idea to use a security certificate whenever you are passing personal information between the website and web server or database. Attackers could sniff for this information and if the communication medium is not secure could capture it and use this information to gain access to user accounts and personal data.

Use an SSL certificate

10. Website security tools

Once you think you have done all you can then it’s time to test your website security. The most effective way of doing this is via the use of some website security tools, often referred to as penetration testing or pen testing for short.

There are many commercial and free products to assist you with this. They work on a similar basis to scripts hackers will use in that they test all know exploits and attempt to compromise your site using some of the previous mentioned methods such as SQL injection.

Some free tools that are worth looking at:

  • Netsparker (Free community edition and trial version available). Good for testing SQL injection and XSS
  • OpenVAS. Claims to be the most advanced open source security scanner. Good for testing known vulnerabilities, currently scans over 25,000. But it can be difficult to setup and requires a OpenVAS server to be installed which only runs on *nix. OpenVAS is fork of a Nessus before it became a closed-source commercial product.

The results from automated tests can be daunting, as they present a wealth of potential issues. The important thing is to focus on the critical issues first. Each issue reported normally comes with a good explanation of the potential vulnerability. You will probably find that some of the medium/low issues aren’t a concern for your site.

If you wish to take things a step further then there are some further steps you can take to manually try to compromise your site by altering POST/GET values. A debugging proxy can assist you here as it allows you to intercept the values of an HTTP request between your browser and the server. A popular freeware application called Fiddler is a good starting point.

So what should you be trying to alter on the request? If you have pages which should only be visible to a logged in user then I would try changing URL parameters such as user id, or cookie values in an attempt to view details of another user. Another area worth testing are forms, changing the POST values to attempt to submit code to perform XSS or to upload a server side script.

Use a debugging proxy to root out vulnerabilities

Hopefully these tips will help keep your site and information safe. Thankfully most CMSes have a lot of inbuilt website security features, but it is a still a good idea to have knowledge of the most common security exploits so you can ensure you are covered.

There are also some helpful modules available for CMSes to check your installation for common security flaws such as Security Review for Drupal and WP Security Scan for WordPress.

Advertisements

To perform the requested action, WordPress needs to access your web server. Please enter your FTP credentials to proceed. If you do not remember your credentials, you should contact your web host


This is very common error for WordPress.

finally I come to see this link, which help me most.

I try to give all the permission for my Project_Dir and stuffs which are just wasting of time.

This simple way i got my problem resolved.

step are as below-

  1. Go to /var/www/html/project_dir.
  2. search for wp-config.php file
  3. Add define(‘FS_METHOD’,’direct’);
  4. Save and exit.

Or we can do the same by terminal

  1. open terminal (ctrl+alt+t).
  2. type cd /var/www/html/project_dir_name.
  3. sudo nano /wp-config.php.
  4. add define(‘FS_METHOD’,’direct’); anywhere you like to add.
  5. press ctrl+x to exit from file.
  6. press‘y’ to save the file.
  7. hit return key (enter).

Have a good day.

Install aptana in Ubuntu machine and open existing project


Install aptana in ubuntu machine.
1). Downloaded the standalone(64 bit version) version.

by using this we can download the aptana,

http://www.aptana.com/products/studio3/download.html
2). Extracted the folder from the zip file.
3). Gave executable permission to Aptana Studio 3 script.
4). Moved the extracted “AptanaStudio3” folder to /opt

How to open existing project in aptana

1. Click on File
2. Select Import from the dropdown menu
3. Select the General tab and open it, you will see the option Existing Folder as New Project
4. Select it and click on Next
5. On the next page select the folder where you have the old project files, name the new project(if you want to change it). You can also select the languages that you have used on the project.
6. Click Finish and you are set to go.

 

Have a great day!!

How To install laravel installer windows xampp or wamp


Install laravel on windows xampp or wamp

Laravel 5.1 is very easy to be install on windows. In this tutorial  we suppose that you have already installed PhP on your machine.

Basic Requirement for Laravel:-

  1. Must have install PhP with a version of 5.5.9 or above like 6.1.3 etc
  2. Windows environment or 64 or 32 bit.
  3. xampp or wamp on machine.

This is the new version and you are getting a new installation feature so guess how fast work is going on updation.

Install laravel on windows xampp/wamp steps :-

1. It’s requires Composer to manage its dependencies. so first need to downloadcomposer

1.1). just follow the process,

1.2). At some point It will ask you to choose the Php.exe file and press next.

1.3). let it be download composer and related setup.
2. Now install composer on your machine.
3. Run below command to check composer has installed successfully

# check composer working
:/> composer

Install laravel via laravel installer windows

4. Now installed successfully we need to install laravel installer via composer so open windows command prompt and run below command to install.

# installing installer
composer global require "laravel/installer=~1.1"

laravel_win4

5. Set PATH environment variable for setup PATH run below command

# setting up env path
set PATH=%PATH%;%USERPROFILE%\AppData\Roaming\Composer\vendor\bin

PATH :- path is a location where composer installed ” ~/.composer/vendor/bin” on Windows path should be used:
“C:\Users\\AppData\Roaming\Composer\vendor\bin” so in above command added “%USERPROFILE%” so this will auto get your computer name

laravel_win5

For test run command laravel to check you have path setuped correctly

# testing command 
laravel -v

Laravel command not found windows :-

This is an optional part if your above testing command not running correct. sometimes if you not setup the PATH correctly you will get Laravel command not found error on windows. for resolve laravel command not found error you need to setup your path environment variable correctly. many times we stuck this error so i am adding this part also. if you have setuped path variable right run command and you will get output success then keep continue with next step to successful installation.

6. Now We need to change directory where we want to install laravel so first change and go to your preferred location to install then run below command to install.

# installing 
laravel new laranew

Now you have done with Install laravel via laravel installer windows(xampp/wamp). and open url on http://localhost/laranew and bam.

laravel_win2

Now Enjoy coding with laravel.

Have a nice day!

Image color change on mouse hover


 

 

In case you want to change color of image on mouse hove.

just copy this complete code and paste in a file, save that with .html extention.

if you run that file you can see the result…

<html>
<body><h1><center>Image color change on mouse hover</center></h1>
<img src="http://www.skyhdwallpaper.com/wp-content/uploads/2014/12/Best-3D-Wallpaper-1.jpg" width="900" height="410" alt="Girl eating apple" class="grayscale" />
</body>
</html>

<style>
@import “bourbon”;

body {
margin: 0 auto ;
width: 80%;
padding: 85px;
}

.grayscale{
border: 2px solid black;
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
filter: gray;
-webkit-transition: all .6s ease;
}
.grayscale:hover {
filter: grayscale(0%);
-webkit-filter: grayscale(0%);
filter: none;
}
</style>

Thanks

Have a nice day!

Eloquent: Relationships in laravel 5


Defining Relationships

Eloquent relationships are defined as functions on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as functions provides powerful method chaining and querying capabilities. For example:

$user->posts()->where('active', 1)->get();

But, before diving too deep into using relationships, let’s learn how to define each type:

One To One

A one-to-one relationship is a very basic relation. For example, a User model might be associated with one Phone. To define this relationship, we place a phone method on the User model. The phone method should return the results of the hasOne method on the base Eloquent model class:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

The first argument passed to the hasOne method is the name of the related model. Once the relationship is defined, we may retrieve the related record using Eloquent’s dynamic properties. Dynamic properties allow you to access relationship functions as if they were properties defined on the model:

$phone = User::find(1)->phone;

Eloquent assumes the foreign key of the relationship based on the model name. In this case, the Phone model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:

return $this->hasOne('App\Phone', 'foreign_key');

Additionally, Eloquent assumes that the foreign key should have a value matching the id column of the parent. In other words, Eloquent will look for the value of the user’s id column in the user_id column of the Phone record. If you would like the relationship to use a value other than id, you may pass a third argument to the hasOne method specifying your custom key:

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

Defining The Inverse Of The Relation

So, we can access the Phone model from our User. Now, let’s define a relationship on the Phone model that will let us access the User that owns the phone. We can define the inverse of a hasOne relationship using the belongsTo method:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

In the example above, Eloquent will try to match the user_id from the Phone model to an id on the User model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method:

/**
 * Get the user that owns the phone.
 */
public function user()
{
    return $this->belongsTo('App\User', 'foreign_key');
}

If your parent model does not use id as its primary key, or you wish to join the child model to a different column, you may pass a third argument to the belongsTo method specifying your parent table’s custom key:

/**
 * Get the user that owns the phone.
 */
public function user()
{
    return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}

One To Many

A “one-to-many” relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

Remember, Eloquent will automatically determine the proper foreign key column on the Comment model. By convention, Eloquent will take the “snake case” name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.

Once the relationship has been defined, we can access the collection of comments by accessing the comments property. Remember, since Eloquent provides “dynamic properties”, we can access relationship functions as if they were defined as properties on the model:

$comments = App\Post::find(1)->comments;

foreach ($comments as $comment) {
    //
}

Of course, since all relationships also serve as query builders, you can add further constraints to which comments are retrieved by calling the comments method and continuing to chain conditions onto the query:

$comments = App\Post::find(1)->comments()->where('title', 'foo')->first();

Like the hasOne method, you may also override the foreign and local keys by passing additional arguments to the hasMany method:

return $this->hasMany('App\Comment', 'foreign_key');

return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

Defining The Inverse Of The Relation

Now that we can access all of a post’s comments, let’s define a relationship to allow a comment to access its parent post. To define the inverse of a hasMany relationship, define a relationship function on the child model which calls the belongsTo method:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

Once the relationship has been defined, we can retrieve the Post model for a Comment by accessing the post “dynamic property”:

$comment = App\Comment::find(1);

echo $comment->post->title;

In the example above, Eloquent will try to match the post_id from the Comment model to an id on the Post model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Comment model is not post_id, you may pass a custom key name as the second argument to the belongsTo method:

/**
 * Get the post that owns the comment.
 */
public function post()
{
    return $this->belongsTo('App\Post', 'foreign_key');
}

If your parent model does not use id as its primary key, or you wish to join the child model to a different column, you may pass a third argument to the belongsTo method specifying your parent table’s custom key:

/**
 * Get the post that owns the comment.
 */
public function post()
{
    return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}

Many To Many

Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of “Admin”. To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

Many-to-many relationships are defined by writing a method that calls the belongsToMany method on the base Eloquent class. For example, let’s define the roles method on our User model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

Once the relationship is defined, you may access the user’s roles using the roles dynamic property:

$user = App\User::find(1);

foreach ($user->roles as $role) {
    //
}

Of course, like all other relationship types, you may call the roles method to continue chaining query constraints onto the relationship:

$roles = App\User::find(1)->roles()->orderBy('name')->get();

As mentioned previously, to determine the table name of the relationship’s joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method:

return $this->belongsToMany('App\Role', 'user_roles');

In addition to customizing the name of the joining table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:

return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');

Defining The Inverse Of The Relationship

To define the inverse of a many-to-many relationship, you simply place another call to belongsToMany on your related model. To continue our user roles example, let’s define the users method on the Role model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

As you can see, the relationship is defined exactly the same as its User counterpart, with the exception of simply referencing the App\User model. Since we’re reusing the belongsToMany method, all of the usual table and key customization options are available when defining the inverse of many-to-many relationships.

Retrieving Intermediate Table Columns

As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let’s assume our User object has many Role objects that it is related to. After accessing this relationship, we may access the intermediate table using the pivot attribute on the models:

$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}

Notice that each Role model we retrieve is automatically assigned a pivot attribute. This attribute contains a model representing the intermediate table, and may be used like any other Eloquent model.

By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:

return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');

If you want your pivot table to have automatically maintained created_at and updated_at timestamps, use the withTimestamps method on the relationship definition:

return $this->belongsToMany('App\Role')->withTimestamps();

Has Many Through

The “has-many-through” relationship provides a convenient short-cut for accessing distant relations via an intermediate relation. For example, a Country model might have many Post models through an intermediate User model. In this example, you could easily gather all blog posts for a given country. Let’s look at the tables required to define this relationship:

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

Though posts does not contain a country_id column, the hasManyThrough relation provides access to a country’s posts via $country->posts. To perform this query, Eloquent inspects the country_id on the intermediate users table. After finding the matching user IDs, they are used to query the posts table.

Now that we have examined the table structure for the relationship, let’s define it on the Country model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    /**
     * Get all of the posts for the country.
     */
    public function posts()
    {
        return $this->hasManyThrough('App\Post', 'App\User');
    }
}

The first argument passed to the hasManyThrough method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.

Typical Eloquent foreign key conventions will be used when performing the relationship’s queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the hasManyThrough method. The third argument is the name of the foreign key on the intermediate model, while the fourth argument is the name of the foreign key on the final model.

class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user_id');
    }
}

Polymorphic Relations

Table Structure

Polymorphic relations allow a model to belong to more than one other model on a single association. For example, imagine you want to store photos for your staff members and for your products. Using polymorphic relationships, you can use a single photos table for both of these scenarios. First, let’s examine the table structure required to build this relationship:

staff
    id - integer
    name - string

products
    id - integer
    price - integer

photos
    id - integer
    path - string
    imageable_id - integer
    imageable_type - string

Two important columns to note are the imageable_id and imageable_type columns on the photos table. The imageable_id column will contain the ID value of the owning staff or product, while the imageable_type column will contain the class name of the owning model. The imageable_type column is how the ORM determines which “type” of owning model to return when accessing the imageable relation.

Model Structure

Next, let’s examine the model definitions needed to build this relationship:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Photo extends Model
{
    /**
     * Get all of the owning imageable models.
     */
    public function imageable()
    {
        return $this->morphTo();
    }
}

class Staff extends Model
{
    /**
     * Get all of the staff member's photos.
     */
    public function photos()
    {
        return $this->morphMany('App\Photo', 'imageable');
    }
}

class Product extends Model
{
    /**
     * Get all of the product's photos.
     */
    public function photos()
    {
        return $this->morphMany('App\Photo', 'imageable');
    }
}

Retrieving Polymorphic Relations

Once your database table and models are defined, you may access the relationships via your models. For example, to access all of the photos for a staff member, we can simply use the photos dynamic property:

$staff = App\Staff::find(1);

foreach ($staff->photos as $photo) {
    //
}

You may also retrieve the owner of a polymorphic relation from the polymorphic model by accessing the name of the method that performs the call to morphTo. In our case, that is the imageable method on the Photo model. So, we will access that method as a dynamic property:

$photo = App\Photo::find(1);

$imageable = $photo->imageable;

The imageable relation on the Photo model will return either a Staff or Product instance, depending on which type of model owns the photo.

Many To Many Polymorphic Relations

Table Structure

In addition to traditional polymorphic relations, you may also define “many-to-many” polymorphic relations. For example, a blog Post and Video model could share a polymorphic relation to a Tag model. Using a many-to-many polymorphic relation allows you to have a single list of unique tags that are shared across blog posts and videos. First, let’s examine the table structure:

posts
    id - integer
    name - string

videos
    id - integer
    name - string

tags
    id - integer
    name - string

taggables
    tag_id - integer
    taggable_id - integer
    taggable_type - string

Model Structure

Next, we’re ready to define the relationships on the model. The Post and Video models will both have a tags method that calls the morphToMany method on the base Eloquent class:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable');
    }
}

Defining The Inverse Of The Relationship

Next, on the Tag model, you should define a method for each of its related models. So, for this example, we will define a posts method and a videos method:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    /**
     * Get all of the posts that are assigned this tag.
     */
    public function posts()
    {
        return $this->morphedByMany('App\Post', 'taggable');
    }

    /**
     * Get all of the videos that are assigned this tag.
     */
    public function videos()
    {
        return $this->morphedByMany('App\Video', 'taggable');
    }
}

Retrieving The Relationship

Once your database table and models are defined, you may access the relationships via your models. For example, to access all of the tags for a post, you can simply use the tags dynamic property:

$post = App\Post::find(1);

foreach ($post->tags as $tag) {
    //
}

You may also retrieve the owner of a polymorphic relation from the polymorphic model by accessing the name of the method that performs the call to morphedByMany. In our case, that is the posts or videos methods on the Tag model. So, you will access those methods as dynamic properties:

$tag = App\Tag::find(1);

foreach ($tag->videos as $video) {
    //
}

Querying Relations

Since all types of Eloquent relationships are defined via functions, you may call those functions to obtain an instance of the relationship without actually executing the relationship queries. In addition, all types of Eloquent relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the SQL against your database.

For example, imagine a blog system in which a User model has many associated Post models:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get all of the posts for the user.
     */
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

You may query the posts relationship and add additional constraints to the relationship like so:

$user = App\User::find(1);

$user->posts()->where('active', 1)->get();

Note that you are able to use any of the query builder methods on the relationship!

Relationship Methods Vs. Dynamic Properties

If you do not need to add additional constraints to an Eloquent relationship query, you may simply access the relationship as if it were a property. For example, continuing to use our User and Post example models, we may access all of a user’s posts like so:

$user = App\User::find(1);

foreach ($user->posts as $post) {
    //
}

Dynamic properties are “lazy loading”, meaning they will only load their relationship data when you actually access them. Because of this, developers often use eager loading to pre-load relationships they know will be accessed after loading the model. Eager loading provides a significant reduction in SQL queries that must be executed to load a model’s relations.

Querying Relationship Existence

When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, imagine you want to retrieve all blog posts that have at least one comment. To do so, you may pass the name of the relationship to the has method:

// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();

You may also specify an operator and count to further customize the query:

// Retrieve all posts that have three or more comments...
$posts = Post::has('comments', '>=', 3)->get();

Nested has statements may also be constructed using “dot” notation. For example, you may retrieve all posts that have at least one comment and vote:

// Retrieve all posts that have at least one comment with votes...
$posts = Post::has('comments.votes')->get();

If you need even more power, you may use the whereHas and orWhereHas methods to put “where” conditions on your has queries. These methods allow you to add customized constraints to a relationship constraint, such as checking the content of a comment:

// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

Eager Loading

When accessing Eloquent relationships as properties, the relationship data is “lazy loaded”. This means the relationship data is not actually loaded until you first access the property. However, Eloquent can “eager load” relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem. To illustrate the N + 1 query problem, consider a Book model that is related to Author:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * Get the author that wrote the book.
     */
    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}

Now, let’s retrieve all books and their authors:

$books = App\Book::all();

foreach ($books as $book) {
    echo $book->author->name;
}

This loop will execute 1 query to retrieve all of the books on the table, then another query for each book to retrieve the author. So, if we have 25 books, this loop would run 26 queries: 1 for the original book, and 25 additional queries to retrieve the author of each book.

Thankfully, we can use eager loading to reduce this operation to just 2 queries. When querying, you may specify which relationships should be eager loaded using the with method:

$books = App\Book::with('author')->get();

foreach ($books as $book) {
    echo $book->author->name;
}

For this operation, only two queries will be executed:

select * from books

select * from authors where id in (1, 2, 3, 4, 5, ...)

Eager Loading Multiple Relationships

Sometimes you may need to eager load several different relationships in a single operation. To do so, just pass additional arguments to the with method:

$books = App\Book::with('author', 'publisher')->get();

Nested Eager Loading

To eager load nested relationships, you may use “dot” syntax. For example, let’s eager load all of the book’s authors and all of the author’s personal contacts in one Eloquent statement:

$books = App\Book::with('author.contacts')->get();

Constraining Eager Loads

Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here’s an example:

$users = App\User::with(['posts' => function ($query) {
    $query->where('title', 'like', '%first%');

}])->get();

In this example, Eloquent will only eager load posts that if the post’s title column contains the word first. Of course, you may call other query builder to further customize the eager loading operation:

$users = App\User::with(['posts' => function ($query) {
    $query->orderBy('created_at', 'desc');

}])->get();

Lazy Eager Loading

Sometimes you may need to eager load a relationship after the parent model has already been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models:

$books = App\Book::all();

if ($someCondition) {
    $books->load('author', 'publisher');
}

If you need to set additional query constraints on the eager loading query, you may pass a Closure to the load method:

$books->load(['author' => function ($query) {
    $query->orderBy('published_date', 'asc');
}]);

Inserting Related Models

The Save Method

Eloquent provides convenient methods for adding new models to relationships. For example, perhaps you need to insert a new Comment for a Post model. Instead of manually setting the post_id attribute on the Comment, you may insert the Comment directly from the relationship’s save method:

$comment = new App\Comment(['message' => 'A new comment.']);

$post = App\Post::find(1);

$comment = $post->comments()->save($comment);

Notice that we did not access the comments relationship as a dynamic property. Instead, we called the comments method to obtain an instance of the relationship. The save method will automatically add the appropriate post_id value to the new Comment model.

If you need to save multiple related models, you may use the saveMany method:

$post = App\Post::find(1);

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);

Save & Many To Many Relationships

When working with a many-to-many relationship, the save method accepts an array of additional intermediate table attributes as its second argument:

App\User::find(1)->roles()->save($role, ['expires' => $expires]);

The Create Method

In addition to the save and saveMany methods, you may also use the create method, which accepts an array of attributes, creates a model, and inserts it into the database. Again, the difference between save and create is that save accepts a full Eloquent model instance while create accepts a plain PHP array:

$post = App\Post::find(1);

$comment = $post->comments()->create([
    'message' => 'A new comment.',
]);

Before using the create method, be sure to review the documentation on attribute mass assignment.

Updating “Belongs To” Relationships

When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:

$account = App\Account::find(10);

$user->account()->associate($account);

$user->save();

When removing a belongsTo relationship, you may use the dissociate method. This method will reset the foreign key as well as the relation on the child model:

$user->account()->dissociate();

$user->save();

Many To Many Relationships

Attaching / Detaching

When working with many-to-many relationships, Eloquent provides a few additional helper methods to make working with related models more convenient. For example, let’s imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach method:

$user = App\User::find(1);

$user->roles()->attach($roleId);

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:

$user->roles()->attach($roleId, ['expires' => $expires]);

Of course, sometimes it may be necessary to remove a role from a user. To remove a many-to-many relationship record, use the detach method. The detach method will remove the appropriate record out of the intermediate table; however, both models will remain in the database:

// Detach a single role from the user...
$user->roles()->detach($roleId);

// Detach all roles from the user...
$user->roles()->detach();

For convenience, attach and detach also accept arrays of IDs as input:

$user = App\User::find(1);

$user->roles()->detach([1, 2, 3]);

$user->roles()->attach([1 => ['expires' => $expires], 2, 3]);

Syncing For Convenience

You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the array will exist in the intermediate table:

$user->roles()->sync([1, 2, 3]);

You may also pass additional intermediate table values with the IDs:

$user->roles()->sync([1 => ['expires' => true], 2, 3]);

Touching Parent Timestamps

When a model belongsTo or belongsToMany another model, such as a Comment which belongs to a Post, it is sometimes helpful to update the parent’s timestamp when the child model is updated. For example, when a Comment model is updated, you may want to automatically “touch” the updated_at timestamp of the owning Post. Eloquent makes it easy. Just add a touches property containing the names of the relationships to the child model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * All of the relationships to be touched.
     *
     * @var array
     */
    protected $touches = ['post'];

    /**
     * Get the post that the comment belongs to.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

Now, when you update a Comment, the owning Post will have its updated_at column updated as well:

$comment = App\Comment::find(1);

$comment->text = 'Edit to this comment!';

$comment->save();


click here to view more

Form validation with Jquery


<html>

             <form action=”” method=”post” id=”register-form” enctype=”multipart/form-data” style=”margin-  bottom:110px;”>

              Name: <input type=”text” name=”name” id=”firstnam name” >

              <input type=”submit” value=”Register Now” name= “Submit”>

              </form>

</html>

//code.jquery.com/jquery-1.9.1.js
//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js

$(function() {
              // Setup form validation on the #register-form element
              $(“#register-form”).validate({
              // Specify the validation rules
              rules: {
                            name: ‘required’,
                            email: {
                            required: true,
                            email: true,
              },
              password: {
                            required: true,
                            minlength: 10,
                            minlength:5,
              },
         }
    });
});

javascript validation for image size, image format & preview uploaded image before upload.


<html>
     <head>

       </head>
       <body>
                  <input type=”file” name=”dataFile” id=”fileChooser” onchange=”return ValidateFileUpload()” />
                 <img src=”images/noimg.jpg” id=”blah”>
     </body>
</html>
function ValidateFileUpload() {
var fuData = document.getElementById(‘fileChooser’);
var FileUploadPath = fuData.value;
var size = parseFloat($(“#fileChooser”)[0].files[0].size / 1024).toFixed(2);
if (size>=10){
alert(“Chossen Image: “+size+”KB. which must be upto 10 KB.”);
return false;
}
if (FileUploadPath == ”) {
alert(“Please upload an image”);
} else {
var Extension = FileUploadPath.substring(
FileUploadPath.lastIndexOf(‘.’) + 1).toLowerCase();
if (Extension == “gif” || Extension == “png” || Extension == “bmp”
|| Extension == “jpeg” || Extension == “jpg”) {
if (fuData.files && fuData.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$(‘#blah’).attr(‘src’, e.target.result);
}
reader.readAsDataURL(fuData.files[0]);
}
}
else {
alert(“Image formate must be GIF, PNG, JPG, JPEG and BMP type only.”);
return false;
}
}
}

click to see more details here

you can just copy and paste the above code and can customized as per your requirement.
thank for your time.

have a good day!!!

How to check for user has confirmed email or not in laravel by confirmed==1


for that just follow the this link to create all thing done.

 

then you ll be get problem to check if confirmed == 1

then only user can get login

for that just

app/vendor/laravel/framework/src/illuminate/Foundation/Auth/AuthenticatesUsers.php

and add this line to get chek for confirmed==1

$credentials = array_add($credentials, ‘confirmed’, ‘1’);

your page must look like this–

public function postLogin(Request $request)

{

$this->validate($request, [

$this->loginUsername() => ‘required’, ‘password’ => ‘required’,

]);

// If the class is using the ThrottlesLogins trait, we can automatically throttle

// the login attempts for this application. We’ll key this by the username and

// the IP address of the client making these requests into this application.

$throttles = $this->isUsingThrottlesLoginsTrait();

if ($throttles && $this->hasTooManyLoginAttempts($request)) {

return $this->sendLockoutResponse($request);

}

$credentials = $this->getCredentials($request);

$credentials = array_add($credentials, ‘confirmed’, ‘1’);

if (Auth::attempt($credentials, $request->has(‘remember’))) {

return $this->handleUserWasAuthenticated($request, $throttles);

}

// If the login attempt was unsuccessful we will increment the number of attempts

// to login and redirect the user back to the login form. Of course, when this

// user surpasses their maximum number of attempts they will get locked out.

if ($throttles) {

$this->incrementLoginAttempts($request);

}

return redirect($this->loginPath())

->withInput($request->only($this->loginUsername(), ‘remember’))

->withErrors([

$this->loginUsername() => $this->getNotConfirmMessage(),

]);

}

I got my task done by following this link but it took many modifications.