Riyad Amin

Riyad Amin

1670231716

Create Custom Validation Rules in Laravel

In most instances, the rules provided by Laravel are sufficient enough to validate all the use cases, but in certain conditions, you might need to add custom validation rules. In this tutorial, learn how to create custom validation rule in Laravel 9.

Create a Form Request

It is a good practice to encapsulate your validation rules in the form request object.

php artisan make:request UserRequest
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'name'=>'required|max:255',
            'email'=>'required|email|unique:users',
            'birth_year'=>'required'
        ];
    }
}

As you can see there are two methods that are already present in the class:

  • Authorize method: It is used to define the authorization rules. It can help you in determining who all has access to these pages.
  • Rules method: This is the method where you would be adding your validation rules. We are validating name, email, and Birth Year.

Creating Rule Class

As we have just seen, we have created a Customer Model that has a name and email. Now let us add some rules to validate these fields. You can execute the below command to create a custom rule.

php artisan make:rule BirthYearRule
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class BirthYearRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return $value >= 1990 && $value <= date('Y');
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return "The :attribute must be between 1990 to ".date('Y').".";
    }
}

As you can see there are two functions that we need to implement in the above class. These are passes() and message().

Adding Validation Logic

Once we have added the validation rule class, let us add the validation logic also. For this example, lets us consider that the birth year is greater than or equal to 1990 and less than or equal to the current year. So we will go ahead and update our passes function.

/**
* Determine if the validation rule passes.
*
* @param  string  $attribute
* @param  mixed  $value
* @return bool
*/
public function passes($attribute, $value)
{
    return $value >= 1990 && $value <= date('Y');
}

As a good coding practice, we should update the message() function. In the message() function, we are specifying the message that would be shown, in case the validation error happens.

/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
    return "The :attribute must be between 1990 to ".date('Y').".";
}

Using the Validation Rule in Form Request Class

Now that we have created the validation rule, let us go ahead and add the validation in the form request class which we had added above.

The first step would be to import this newly created class into our request class. We can import using the below code:

use App\Rules\BirthYearRule;

Now that we have imported the class, let us go ahead and update and update the rules() method.

/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
    return [
        'name'=>'required|max:255',
        'email'=>'required|email|unique:users',
        'birth_year'=>['required', new BirthYearRule]
    ];
}

As you can see, we now have added an extra validation in the name rules list. We are creating a new instance of the BirthYearRule class. When the rules() method will get executed, the BirthYearRule class will be instantiated and it will call the passes() method in the BirthYearRule class to validate the name.

Using the Validation Rule in Controller

The above method of adding the rule in the form request is useful when you are creating the request object. The rules class can also be added directly to the controller code. Let us quickly see how we can implement the BirthYearRule class directly in the controller.

Again, the first step would be to import the BirthYearRule directly into the controller class. We can use the below code to directly import the class.

use App\Rules\BirthYearRule;

Once you have imported the class, the next step would be adding in the validate call.

$request->validate([
    'name'=>'required|max:255',
    'email'=>'required|email|unique:users',
    'birth_year'=>['required', new BirthYearRule]
])

As you can see in the request validate function, we added a new rule in name validation. We are creating a new object of the BirthYearRule class. During this call, a new object of BirthYearRule will be created, and validation will take place.

Custom Validation Rule Using Closures

Now that we have seen how we can create our custom validation rules using the make:rule command, we should understand how we can create commands using closures. The concept of the validation rule remains the same, it is just implemented in a different form.

$validator = Validator::make($request->post(),[
    'birth_year'=>[
        'required',
        function($attribute, $value, $fail){
            if($value >= 1990 && $value <= date('Y')){
                $fail("The :attribute must be between 1990 to ".date('Y').".");
            }
        }
    ]
]);

As we can see in the above code, we are using the Validator class and directly making the rule. The function in it is getting 3 values: attribute, value, and fail. The attribute is the field for which the validation is happening. The value corresponds to the actual value of the said object and failure is the callback method that would be executed once the validation fails.

Happy Coding !!!

Originally published by https://techvblogs.com 

#laravel #php 

What is GEEK

Buddha Community

Create Custom Validation Rules in Laravel
Easter  Deckow

Easter Deckow

1655630160

PyTumblr: A Python Tumblr API v2 Client

PyTumblr

Installation

Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install

Usage

Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
                    source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",
                    data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
                    embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

I am Developer

1604492424

Laravel 8 Custom Validation Error Messages Example

Laravel 8 custom validation rules and error messages. In this tutorial, i will show you how to add custom validation rules and display custom validation error messages in laravel 8 app.

Laravel 8 Custom Validation Rule & Error Message Example

  • Step 1 - Install Laravel 8 App
  • Step 2 - Connecting App to Database
  • Step 3 - Run Migration Command
  • Step 4 - Add Routes
  • Step 5 - Generate Controller By Command
  • Step 6 - Create the blade view
  • Step 7 - Run Development Server

https://www.tutsmake.com/laravel-8-custom-validation-error-messages-tutorial/

#laravel custom validation rule with parameters #laravel custom validation message #laravel request validation custom message #laravel custom validation error messages

Hertha  Mayer

Hertha Mayer

1594769515

How to validate mobile phone number in laravel with example

Data validation and sanitization is a very important thing from security point of view for a web application. We can not rely on user’s input. In this article i will let you know how to validate mobile phone number in laravel with some examples.

if we take some user’s information in our application, so usually we take phone number too. And if validation on the mobile number field is not done, a user can put anything in the mobile number field and without genuine phone number, this data would be useless.

Since we know that mobile number can not be an alpha numeric or any alphabates aand also it should be 10 digit number. So here in this examples we will add 10 digit number validation in laravel application.

We will aalso see the uses of regex in the validation of mobile number. So let’s do it with two different way in two examples.

Example 1:

In this first example we will write phone number validation in HomeController where we will processs user’s data.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('createUser');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
                'name' => 'required',
                'phone' => 'required|digits:10',
                'email' => 'required|email|unique:users'
            ]);

        $input = $request->all();
        $user = User::create($input);

        return back()->with('success', 'User created successfully.');
    }
}

Example 2:

In this second example, we will use regex for user’s mobile phone number validation before storing user data in our database. Here, we will write the validation in Homecontroller like below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Validator;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('createUser');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
                'name' => 'required',
                'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
                'email' => 'required|email|unique:users'
            ]);

        $input = $request->all();
        $user = User::create($input);

        return back()->with('success', 'User created successfully.');
    }
}

#laravel #laravel phone number validation #laravel phone validation #laravel validation example #mobile phone validation in laravel #phone validation with regex #validate mobile in laravel

Laravel 8 Create Custom Helper Function Example

Today, We will see laravel 8 create custom helper function example, as we all know laravel provides many ready mate function in their framework, but many times we need to require our own customized function to use in our project that time we need to create custom helper function, So, here i am show you custom helper function example in laravel 8.

Laravel 8 Create Custom Helper Function Example

https://websolutionstuff.com/post/laravel-8-create-custom-helper-function-example


Read Also : Cron Job Scheduling In Laravel

https://websolutionstuff.com/post/cron-job-scheduling-in-laravel

#laravel 8 create custom helper function example #laravel #custom helper function #how to create custom helper in laravel 8 #laravel helper functions #custom helper functions in laravel

I am Developer

1597565398

Laravel 7/6 Image Validation

In this image validation in laravel 7/6, i will share with you how validate image and image file mime type like like jpeg, png, bmp, gif, svg, or webp before uploading image into database and server folder in laravel app.

https://www.tutsmake.com/image-validation-in-laravel/

#laravel image validation #image validation in laravel 7 #laravel image size validation #laravel image upload #laravel image validation max #laravel 6 image validation