Showing posts with label laravel. Show all posts
Showing posts with label laravel. Show all posts

Laravel Blade Template Bootstrap Form Example


  • Blade Form Select Option 

Blade Form Template code for Select.

{{Form::select( 'revenue_var', $revDistrict , (isset($data) && !empty( $data )) ? $data['dist_id'] : ' ', ['class' => 'form-control required', 'tabindex'=>$tabindex++, 'placeholder'=> '----Select District.----']) }}

(isset($data) && !empty( $data )) ? $data['dist_id'] : ' '

The isset() method checks whether a variable is set and declared and is not NULL. isset() function returns true value if the variable exists and is not NULL or it will returns false.

empty() method checks whether variable is empty or not. empty() function return false if variable exists and is not empty, or it will returns true.

Ternary Operator [ ?: ]

( ExpressionA ? ExpressionB : ExpressionC )

(isset($data) && !empty( $data )) ? $data['dist_id'] : '  '


In this ExpressionA is evaluated first. If ExpressionA will be True then ExpressionB will be executed and the result will be returned. Otherwise, if the ExpressionA is false then ExpressionC will be executed and the result will be returned.


  • Blade Form Text Field


{{ Form::text( 'name', (isset($data) && !empty( $data )) ? $data['name'] : '  ', ['class' => 'form-control ', 'tabindex'=>$tabindex++, 'placeholder'=>'Enter Name'] ) }}

Blade Form Template code for Textbox.

  • Blade Form Radio Field


{{ Form::radio('gender', 'MALE ', true , (isset($data) && !empty($data) && $data['gender'] == 'MALE') ? true : false,  array("required")) }}

{{ Form::radio('gender' , 'FEMALE', false , (isset($data) && !empty($data) && $data['gender'] == 'FEMALE')  ? true : false ) }}

Blade Form Template code for Radio


  • Blade Form Checkbox Field


{{ Form::checkbox( 1stArgument, 2ndArgument, 3rdArgument, 4thArgument ) }}

First argument : name
Second argument : value
Third argument : checked or not checked this takes: true or false
Fourth argument : additional attributes (e.g., checkbox css classe)



Laravel HTTP Request, Methods and Input


Laravel HTTP Request

Laravel HTTP(HyperText Transfer Protocol) request method is the way to structure the request and response to set the communication of Client and server or its a protocol to transfer the data over the web. Http follow the server-client Model. In Laravel HTTP request get processed through routes/web.php by default.

We can access the Http Request by declearing the Illuminate\Http\Request in Controller.

public function personalData(Request $request)
    {
        $name = $request->input('name'); 
    }

HTTP Request Path and Methods

Illuminate\Http\Request instance provides various method to access the Http request and its parameter which is trying to access the application.

path() method will return the information about the url path. For example: Our URL is https://www.abcd.com/my-profile/umesh, if we use path() method to get the request it will return /my-profile/umesh. 

For Example : 
$uriPath = $request->path();

We can fetch the entire url itself using url() method  and fullurl() method. ce url method will return the url without string whereas fullurl method will return with string. Below is the code for your reference.
$urlWthtString = $request->url();  // return url without String
$urlWthString = $request->fullUrl(); // return url with String

Fetching the Request Method

We can fetch the HTTP request type using method() function as well as we can check whether the requested method is satisfying the type using ismethod() function . 

$methodType = $request->method();
// This Will give you the request method type whether it is post, get etc..

if ($request->isMethod('post')) {
    //
}

Laravel Retrieving Input From HTTP Request 


We can retrieve all the input data as a array which is coming through the HTTP Request using all() method.

$inputData = $request->all();

Illuminate\Http\Request instance We can get the request data using input method. we can pass the second argument in input method. If input method don't have the value it will take second argument as default value. See the code below for reference.

$firstName = $request->input('firstName');
$firstName = $request->input('firstName', 'Umesh');
   
We can use input() method without having any argument to get the input value as a associative array.

$input = $request->input();  // this return the input as a associative array.

Checking Input Value is Present or not


We can check whether the input value is there or not, we use has() method. has() method will return the value as true or false.
if ($request->has('firstName')){
   // $request->has('firstName') will return the value as true or false.   
}
⇛ has() method will check the array input also. check the code below for reference.
if ($request->has(['firstName', 'emailId'])){
    // If both array input will be there, It will return true or false.
}

⇛ hasAny() method will check if any input will be there it will return true. Below is the code for your reference.
if ($request->hasAny(['firstName', 'emailId'])){
    // if any Input will be there it will return true
}

Redirecting and Flashing the input


If the validation fails we need to redirect to the same page with the input. Flashing the input with redirect on the page we use withInput() method. Below is the code for your reference.
return redirect('personal-form/save')->withInput();

return redirect('personal-form/save')->withInput($request->except('userpass'));

Handling File Upload using HTTP Request


Sometime we need to access the uploaded file using HTTP request using file() method. The Illuminate\Http\UploadedFile class have file() method which returns an instance. We can check using hasFile() method that HTTP request have the file or not. Below is the code for your reference.

$fileImage = $request->file('candidate_photo');
$fileImage = $request->candidate_photo;
if ($request->hasFile('candidate_photo')){ // }

Uploaded File Path and Extension 


UploadFile class provide some predefined method through which we can access the file path and its Extension.

$Photopath = $request->candidate_photo->path();

$photoextension = $request->candidate_photo->extension();

Laravel Routing and Named Route with Example

laravel Route List and Resource

Concept of Laravel Routing, Resource and list


Laravel Routes are defined in web.php file which is called by default and resides in routes directory. URL prefix is applied directly and automatically in laravel, you don't have to apply the prefix to each route individually. Router methods list are available like get, post, put, patch, delete, any. 

Any form request which point to Route method like post, put, patch, delete you must have to include the csrf token field.

Basic Route Example :

Route::get('/', function () {
    return 'Welcome to Laravel Basic Routing.';
});

Route::get('/user-profile', 'ProfileController@showProfile');

Redirecting Route to another Route in Laravel

Laravel provide redirect route to another route facility. if you want to redirect the one route to another route. Route redirect return 302 status by default, we can customize the status code using third parameter. See the below code for above two statement.

Route::redirect(' /one-route ', '/other-route');
Route::redirect(' /one-route ', '/other-route', 301);

View Route in Laravel

Route::View method is one useful method in laravel which we can use if we want to show the view only. This provide the shortcut way to redirect the route to view without defining all the route and controller. 

Route::view method accepts three parameter, one is URL string, second argument is view name and third argument is some additional parameter as a array. Below is the code for reference.

Route::view('/my-profile', 'user-profile');
Route::view('/my-profile', 'user-profile', ['name' => 'Umesh']);


Laravel Named Route


Named Route is a friendly name given to the route the reference. We can use Named rout to specify the particular Route as well as to generate the URL / to redirect to specific URL.

Route::post('profile-data/save', 'ProfileController@saveProfile')
->name('profileData');

You must keep the route name always unique. Generating / Redirecting Url for Names Route is below for your reference.

$url = route('profile');
return redirect()->route('profile');

With Name Route we can pass the second or third parameter as a argument.

Route::post('profile-data/{id}', 'ProfileController@updateProfile')
->name('profileData');

To pass the parameter as argument in the named Route code is below for your reference.

$url = route('profile', ['id'=>1 ]);

If we pass the additional parameter in the array, that will be automatically added in the URL generated query String. Below is the example for reference.

$url = route('profile-data/{id}', ['id' => 1, 'rollno' => '1004']);
URL String generated is below /1/profile?rollno=1004

Laravel Route Prefix Defination

Laravel prefix method can add the prefix to the group of route with given URL. Simple example is most of the web application have the admin section. Now as a developer I want to add admin as a prefix to all the route which point to admin pages. Below is the code for your reference.

Route::prefix('admin')->group(function () {
   
        // You have to define all your route here.
    
});

Apply Middleware on Route

We can assign the middleware to the group of route in the routes Directory. As we know that Middleware act as the middle man between the HTTP request and Application,  it filter and restrict the unwanted HTTP request to access the application. Below is the code for reference.

Route::middleware(['AdminMiddleware', 'AuthMiddleware'])->group(function () {
    
 // Specify All the route in this group.
 
});

Laravel Fallback Route

Route::fallback method is another feature of  Laravel Routing in which we handle the HTTP request which do not match with our route list. By default laravel render the 404 not found page using exception handler. Now laravel fallback method you can define and redirect to the view which will get execute if not HTTP request matches.

You must always define the Route::fallback method at the last of route file. Below is the code for your reference.

Route::fallback(function() {
    return 'You have landed on wrong url. ';
});

Current Route Access  

We can Access the current route which is handling the HTTP request  using current,  currentRouteName and currentRouteAction methods. Below is the code example for your reference.

$currentRoute = Route::current();
$routeName = Route::currentRouteName();
$routeAction = Route::currentRouteAction();

Validation in Laravel with Example

Validation in Laravel


Laravel Validation is the way through which we can verify and filter the data coming to the Application database. We can have clean and validated data in the database coming with HTTP with powerful validation rule.

As we know that we store the data in the Database using form. As we must not fill our database with junk and invalid data, we do form validation in client Side as well as server side. The validation in laravel purpose is to get the exact data what is required for application.

Route::get('personal-detail/show', 'PersonalController@showForm');
Route::post('personal-detail/save', 'PersonalController@savePersonalData');

Above two route, One route purpose is to show the Personal Detail form other is to save the personal data in the database. While saving the blog data we will validate all the data format and blog post then we will store in database.

Personal Form Code is below:

<body>
<div class="container" style="width:80%; margin-left:10%;margin-right:10%">
  <h2>Validation form</h2><br/>
  
   {!! Form::open(['url'=>'form-validation/save','id'=>'savePostMaster', 'class' => 'formstyle']) !!}
    <div class="form-group">
      <label for="fullname">Full Name:</label>
      {!! Form::text('FULL_NAME','',array('class'=>'form-control ','id'=>'FULL_NAME','placeholder'=>'Enter Your Full Name')) !!}
      <span class="error" style="color:red"> @if($errors->has('FULL_NAME')) {{ $errors->first('FULL_NAME') }} @endif</span>
    </div>
    <div class="form-group">
      <label for="mobile">Mobile Number:</label>
      {!! Form::text('mobile','',array('class'=>'form-control','id'=>'mobilr','placeholder'=>'Enter Mobile Number')) !!}
      <span class="error" style="color:red"> @if($errors->has('mobile')) {{ $errors->first('mobile') }} @endif</span>
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      {!! Form::email('email','',array('class'=>'form-control','id'=>'email','placeholder'=>'Enter Email ID')) !!}
      <span class="error" style="color:red"> @if($errors->has('email')) {{ $errors->first('email') }} @endif</span>     
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  {!!form::close()!!}
</div>

</body>

 O/P of above code.

laravel form validation

We use laravel Validate function to implement the validation rules in the controller, if the validation method fails then it will halt the execution of code further and it will redirect to the form with error message. We will write the validation logic in PersonalController.

Below is the validation code for your reference purpose.

Validation in Laravel Example


public function saveFormVal(Request $request){         $input = Input::all();         // Validation Code Starts Here         $validatedData = $request->validate([             'FULL_NAME' => 'required|max:25',             'mobile' => 'required|digits:10|unique:valid_table,mobile',             'email' => 'required|email|max:255',         ]);              }

If You will see the above validation code we have applied various validation rules to filter the input Data coming through the HTTP Request. Input field named with FULL_NAME, mobile, email all have certain condition. Like these input field can't be NULL, the mobile number cant be duplicate as well as it must have 10 digit and email id format must be maintain.

If any Input field will not satisfy the condition then validation will fail and it will redirect back with validation error message. See the below image for your reference.

Validation Error message
Refer the input field, User tried to insert the mobile number which have 9 digit as well as the email Id format is not maintain. so these data is junk data which don't serve the purpose.

Here Validation comes in picture, It will filter this all type of unwanted data and will not allow them to store in the database.  


To show all the error on the view add below code.

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div> 
@endif

This above code will print all the validation error message in list format. Above Image is the example which you can refer.

If you want to print all the validation message below the respective input field then you must specify with validation first() method. Below code is there for your reference.

{!! Form::open(['url'=>'form-validation/save','id'=>'savePostMaster', 'class' => 'formstyle']) !!}
    
   <div class="form-group">
      <label for="fullname">Full Name:</label>
      {!! Form::text('FULL_NAME','',array('class'=>'form-control ','id'=>'FULL_NAME','placeholder'=>'Enter Your Full Name')) !!}
      <span class="error" style="color:red"> @if($errors->has('FULL_NAME')) {{ $errors->first('FULL_NAME') }} @endif</span>
    </div>

    <div class="form-group">
      <label for="mobile">Mobile Number:</label>
      {!! Form::text('mobile','',array('class'=>'form-control','id'=>'mobilr','placeholder'=>'Enter Mobile Number')) !!}
      <span class="error" style="color:red"> @if($errors->has('mobile')) {{ $errors->first('mobile') }} @endif</span>
    </div>

    <div class="form-group">
      <label for="email">Email:</label>
      {!! Form::email('email','',array('class'=>'form-control','id'=>'email','placeholder'=>'Enter Email ID')) !!}
      <span class="error" style="color:red"> @if($errors->has('email')) {{ $errors->first('email') }} @endif</span>     
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>

  {!!form::close()!!}

In the above code we have specify the validation error code for each input field which will highlight the error if any validation fails. Below is the image for your reference.

Laravel Validation Error
If any input field will not meet the validation requirement then the Error message will be shown below the Input field.










Some validation Rule list which you can apply on the input filed to get the exact user data to serve our purpose.

Laravel Validation Rules


Validation Rule
Purpose
required
Required validation will ensure that input field must not be null.
alpha
Alpha will ensure that input field must have only Alphabetic Character
Alpha_num
Alpha_nun will check that input field will have only alphabet and Numeric as a input.
digits:value
Digits will ensure that the input filed data must have only numeric data with exact digit length.
digits_between:min,max
Digits_between will check that the input data coming through HTTP request must have numeric data only as well as it must contain the digit in between the specified length.
email:value
Email validation rule will check and ensure that proper email format is given which is followed worldwide.
image
Image will ensure that the uploaded file in the form must be in valid image format. Like JPG, PNG, JPEG, SVG, BMP, GIF etc.
integer
This will ensure that input data will have only integer value only.
ip
This will ensure that the entered value for input field must have in IP Format.
min:value
Min validate that the input field data must have minimum digit.
max:value
Max validation rule ensure that input field must not have greater than the specified digit.
not_regex:pattern
This will ensure that the given data must match with given regular expression.
required_if:anotherfield,value,...
This will check based on the other input field. If first input value is there then the next input field is required.
unique:table,column
This will ensure that the entered data must not have the duplicate value in the specified table column.

Validation Code and Rules Example below with Example and Explanation.


'password' => 'required|min:8|confirmed',
'password_confirmation' => 'required',

'PICK_TEXT'=>'required|max:200',

'code'=> 'required|unique:educational_district,code|digits:3',

'STORE_INDEX_SEQUENCE'=>'required|integer',

'file' => 'required|max:204800|mimes:pdf',

'nadid'=>'required|min:9|max:12|unique:ENTRACNEDOCUMENTMST,
DOCUMENTNUMBER,'.Input::get('id').'|confirmed|
regex:/^[A-Z][A-Z0-9.,$;]+$/',

'nadid_confirmation'=>'required|min:9|max:12',

'sms_email' => 'required|not_in:0',                   
'senderid'=>'required_if:sms_email,==,1',
'email_from'=>'required_if:sms_email,==,2',

'status' => 'required',
'remarks' => 'required_if:status,==,0,2,3,5',

'approved_status' => 'required',
'capacity_applied' => 'required|integer',
'capacity_approved' => 'required_if:approved_status,==,1|integer|
lte:capacity_applied',

'remarks' => 'required_if:approved_status,==,0,2,3',

'image' => 'required:max:204800|mimes:jpeg,jpg,bmp,pdf,png'

'class_id' => 'required|not_in:0',

'code'=> 'required|unique:mp_constituencies,code,'.$mp_constituency->id.',id',

'mobile_no'     => 'required|integer|digits:10',

Using Eloquent in Validation 

'email' => 'unique:App\User,email_address'

Create Validators Manually 


If we don't want to use validate() method, then we can create validators manually using validation Facades.We use make() method to create manual validator.
   
use Illuminate\Support\Facades\Validator;

 $validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'mobile' => 'required|digits:10',
        ]);

        if ($validator->fails()) {
            return redirect('/personal-details')
                        ->withErrors($validator)
                        ->withInput();
        }


Instead of writing url redirection validation code once the validation fails, you can use auto url redirection using validate method. You have to call the instance.

$validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'mobile' => 'required|digits:10',
        ])->validate();



Laravel Validation Form Example :


<div style="background-color:white">
  <h2>Laravel Form Validation Example</h2>
  <form method="POST" action="/form-validation" autocomplete="off">
    @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br/>
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
    @endif
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <div class="row">
      <div class="col-md-12">
        <div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
          <label for="firstname">Full Name:</label>
          <input type="text" id="fullname" name="fullname" class="form-control" placeholder="Enter Full Name" value="{{ old('firstname') }}">
          <span class="text-danger">{{ $errors->first('fullname') }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="form-group {{ $errors->has('emailid') ? 'has-error' : '' }}">
          <label for="emailid">Email ID:</label>
          <input type="text" id="emailid" name="emailid" class="form-control" placeholder="Enter Email ID" value="{{ old('emailid') }}">
          <span class="text-danger">{{ $errors->first('emailid') }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="form-group {{ $errors->has('mobileno') ? 'has-error' : '' }}">
          <label for="mobileno">Mobile No:</label>
          <input type="text" id="mobileno" name="mobileno" class="form-control" placeholder="Enter Mobile No" value="{{ old('mobileno') }}">
          <span class="text-danger">{{ $errors->first('mobileno') }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-6">
        <div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
          <label for="password">Password:</label>
          <input type="password" id="password" name="password" class="form-control" placeholder="Enter Password" >
          <span class="text-danger">{{ $errors->first('password') }}</span>
        </div>
      </div>
      <div class="col-md-6">
        <div class="form-group {{ $errors->has('confirmpassword') ? 'has-error' : '' }}">
          <label for="confirmpassword">Confirm Password:</label>
          <input type="password" id="confirmpassword" name="confirmpassword" class="form-control" placeholder="Enter Confirm Passowrd">
          <span class="text-danger">{{ $errors->first('confirmpassword') }}</span>
        </div>
      </div>
    </div>
    <div class="form-group">
      <button class="btn btn-success">Submit</button>
    </div>
  </form>
</div>



Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post