Showing posts with label Laravel. Show all posts
Showing posts with label Laravel. Show all posts

Laravel ClassLoader trying to load an old version of class

Laravel ClassLoader trying to load an old version of class throws an error 'failed to open stream: No such file or directory'

How to solve this problem?

Clear composer cache and then run composer dump-autoload.
composer clear-cache
composer dump-autoload

Laravel file cache API

Laravel provides an expressive, unified API for various caching backends. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the filesystem. For larger applications, it is recommended that you use a more robust driver such as Memcached or Redis. You may even configure multiple cache configurations for the same driver. Here we listing some file cache API using in laravel

array many(array $keys)

Retrieve multiple items from the cache by key.
Items not found in the cache will have a null value.
Parameters
     array $keys
Return Value
     array


void putMany(array $values, float|int $minutes)

Store multiple items in the cache for a given number of minutes.
Parameters
     array $values
     float|int $minutes
Return Value
     void

void __construct(Filesystem $files, string $directory)

Create a new file cache store instance.
Parameters
     Filesystem $files
     string $directory
Return Value
     void

mixed get(string|array $key)

Retrieve an item from the cache by key.
Parameters
     string|array $key
Return Value
     mixed

void put(string $key, mixed $value, float|int $minutes)

Store an item in the cache for a given number of minutes.
Parameters
     string $key
     mixed $value
     float|int $minutes
Return Value
     void

int|bool increment(string $key, mixed $value = 1)

Increment the value of an item in the cache.
Parameters
     string $key
     mixed $value
Return Value
     int|bool

int|bool decrement(string $key, mixed $value = 1)

Decrement the value of an item in the cache.
Parameters
     string $key
     mixed $value
Return Value
     int|bool

void forever(string $key, mixed $value)

Store an item in the cache indefinitely.
Parameters
     string $key
     mixed $value
Return Value
     void

bool forget(string $key)

Remove an item from the cache.
Parameters
     string $key
Return Value
     bool

bool flush()

Remove all items from the cache.
Return Value
     bool

Filesystem getFilesystem()

Get the Filesystem instance.
Return Value
     Filesystem

string getDirectory()

Get the working directory of the cache.
Return Value
     string

string getPrefix()

Get the cache key prefix.
Return Value
     string

Laravel Validation Rules

Laravel provides several different approaches to validate your application's incoming data. By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.

Available Validation Rules

Below is a list of all available validation rules and their function:

accepted

The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.

active_url

The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function.
after:date

The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function:

'start_date' => 'required|date|after:tomorrow'

Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

after_or_equal:date

The field under validation must be a value after or equal to the given date. For more information, see the after rule.

alpha

The field under validation must be entirely alphabetic characters.

alpha_dash

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alpha_num

The field under validation must be entirely alpha-numeric characters.

array

The field under validation must be a PHP array.

before:date

The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function.

before_or_equal:date

The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP strtotime function.

between:min,max

The field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in the same fashion as the size rule.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

confirmed

The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

date

The field under validation must be a valid date according to the strtotime PHP function.

date_format:format

The field under validation must match the given format. You should use either date or date_format when validating a field, not both.

different:field

The field under validation must have a different value than field.

digits:value

The field under validation must be numeric and must have an exact length of value.

digits_between:min,max

The field under validation must have a length between the given min and max.

dimensions

The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters:

'avatar' => 'dimensions:min_width=100,min_height=200'

Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.

A ratio constraint should be represented as width divided by height. This can be specified either by a statement like 3/2 or a float like 1.5:

'avatar' => 'dimensions:ratio=3/2'

Since this rule requires several arguments, you may use the Rule::dimensions method to fluently construct the rule:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);


distinct

When working with arrays, the field under validation must not have any duplicate values.

'foo.*.id' => 'distinct'

email

The field under validation must be formatted as an e-mail address.

exists:table,column

The field under validation must exist on a given database table.
Basic Usage Of Exists Rule

'state' => 'exists:states'

Specifying A Custom Column Name

'state' => 'exists:states,abbreviation'

Occasionally, you may need to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name using "dot" syntax:

'email' => 'exists:connection.staff,email'

If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit them:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::exists('staff')->where(function ($query) {
            $query->where('account_id', 1);
        }),
    ],
]);


file

The field under validation must be a successfully uploaded file.

filled

The field under validation must not be empty when it is present.

image

The file under validation must be an image (jpeg, png, bmp, gif, or svg)

in:foo,bar,...

The field under validation must be included in the given list of values. Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);


in_array:anotherfield

The field under validation must exist in anotherfield's values.

integer

The field under validation must be an integer.

ip

The field under validation must be an IP address.

ipv4

The field under validation must be an IPv4 address.

ipv6

The field under validation must be an IPv6 address.

json

The field under validation must be a valid JSON string.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

mimetypes:text/plain,...

The file under validation must match one of the given MIME types:

'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client provided MIME type.

mimes:foo,bar,...

The file under validation must have a MIME type corresponding to one of the listed extensions.

Basic Usage Of MIME Rule

'photo' => 'mimes:jpeg,bmp,png'

Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file's contents and guessing its MIME type.

A full listing of MIME types and their corresponding extensions may be found at the following location: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

nullable

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

not_in:foo,bar,...

The field under validation must not be included in the given list of values.

numeric

The field under validation must be numeric.

present

The field under validation must be present in the input data but can be empty.

regex:pattern

The field under validation must match the given regular expression.

Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

required

The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:

    The value is null.
    The value is an empty string.
    The value is an empty array or empty Countable object.
    The value is an uploaded file with no path.

required_if:anotherfield,value,...

The field under validation must be present and not empty if the anotherfield field is equal to any value.

required_unless:anotherfield,value,...

The field under validation must be present and not empty unless the anotherfield field is equal to any value.

required_with:foo,bar,...

The field under validation must be present and not empty only if any of the other specified fields are present.

required_with_all:foo,bar,...

The field under validation must be present and not empty only if all of the other specified fields are present.

required_without:foo,bar,...

The field under validation must be present and not empty only when any of the other specified fields are not present.

required_without_all:foo,bar,...

The field under validation must be present and not empty only when all of the other specified fields are not present.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.

string

The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.

timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:table,column,except,idColumn

The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.

Specifying A Custom Column Name:

'email' => 'unique:users,email_address'

Custom Database Connection

Occasionally, you may need to set a custom connection for database queries made by the Validator. As seen above, setting unique:users as a validation rule will use the default database connection to query the database. To override this, specify the connection and the table name using "dot" syntax:

'email' => 'unique:connection.users,email_address'

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);


If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

'email' => Rule::unique('users')->ignore($user->id, 'user_id')

Adding Additional Where Clauses:

You may also specify additional query constraints by customizing the query using the where method. For example, let's add a constraint that verifies the account_id is 1:

'email' => Rule::unique('users')->where(function ($query) {
    $query->where('account_id', 1);
})

url

The field under validation must be a valid URL.

What is Laravel

Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern. Some of the features of Laravel are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance, and its orientation toward syntactic sugar.

Laravel is regarded as one of the most popular PHP frameworks, together with Symfony, Nette, CodeIgniter, Yii2 and other frameworks.

The following features serve as Laravel's key design points

  • Bundles provide a modular packaging system since the release of Laravel 3, with bundled features already available for easy addition to applications. Furthermore, Laravel 4 uses Composer as a dependency manager to add framework-agnostic and Laravel-specific PHP packages available from the Packagist repository.
  • Eloquent ORM (object-relational mapping) is an advanced PHP implementation of the active record pattern, providing at the same time internal methods for enforcing constraints on the relationships between database objects. Following the active record pattern, Eloquent ORM presents database tables as classes, with their object instances tied to single table rows.
  • Query builder, available since Laravel 4, provides a more direct database access alternative to the Eloquent ORM. Instead of requiring SQL queries to be written directly, Laravel's query builder provides a set of classes and methods capable of building queries programmatically. It also allows selectable caching of the results of executed queries.
  • Application logic is an integral part of developed applications, implemented either by using controllers or as part of the route declarations. The syntax used to define application logic is similar to the one used by Sinatra framework.
  • Reverse routing defines a relationship between the links and routes, making it possible for later changes to routes to be automatically propagated into relevant links. When the links are created by using names of existing routes, the appropriate uniform resource identifiers (URIs) are automatically created by Laravel.
  • Restful controllers provide an optional way for separating the logic behind serving HTTP GET and POST requests.
  • Class auto loading provides automated loading of PHP classes without the need for manual maintenance of inclusion paths. On-demand loading prevents inclusion of unnecessary components, so only the actually used components are loaded.
  • View composers serve as customizable logical code units that can be executed when a view is loaded.
  • Blade templating engine combines one or more templates with a data model to produce resulting views, doing that by transpiling the templates into cached PHP code for improved performance. Blade also provides a set of its own control structures such as conditional statements and loops, which are internally mapped to their PHP counterparts. Furthermore, Laravel services may be called from Blade templates, and the templating engine itself can be extended with custom directives.
  • IoC containers make it possible for new objects to be generated by following the inversion of control (IoC) principle, in which the framework calls into the application- or task-specific code, with optional instantiating and referencing of new objects as singletons.
  • Migrations provide a version control system for database schemas, making it possible to associate changes in the application's codebase and required changes in the database layout. As a result, this feature simplifies the deployment and updating of Laravel-based applications.
  • Database seeding provides a way to populate database tables with selected default data that can be used for application testing or be performed as part of the initial application setup.
  • Unit testing is provided as an integral part of Laravel, which itself contains unit tests that detect and prevent regressions in the framework. Unit tests can be run through the provided artisan command-line utility.
  • Automatic pagination simplifies the task of implementing pagination, replacing the usual manual implementation approaches with automated methods integrated into Laravel.
  • Form request is a feature of Laravel 5 that serves as the base for form input validation by internally binding event listeners, resulting in automated invoking of the form validation methods and generation of the actual form.
  • Homestead - a Vagrant virtual machine that provides Laravel developers with all the tools nessessary to develop Laravel straight out of the box, including, Ubuntu, Gulp , Bower and other development tools that are useful in developing full scale web applications.


How can i check the request is AJAX in laravel

How can i check the request is ajax in laravel framework.

You can easily check the request is ajax or not. First you paste the below line into the top of the controller page.

use Illuminate\Http\Request;

This is the sample code
public function SomeFunction(Request $HTTPRequest)
{
      if($HTTPRequest->ajax())
      {
            //Yes it is an ajax request
      }
      else
     {
          //It is not an ajax request
     }
}