Laravel custom validation for three inputs - php

I need to make a custom validation rule where for these three inputs where net_weight = loaded_weight - empty_weight
<fieldset class="form-group">
<div class="form-group">
<label for="text">empty weight</label>
<input type="number" class="form-control form-control-lg" id="empty_weight"
name="empty_weight" min="15000" max="35000" step="20" oncopy="return false"
onpaste="return false">
</div>
</fieldset>
<fieldset>
<legend class="h5 text-center text-danger">loaded weight</legend>
<div class="form-group">
<input type="number" class="form-control form-control-lg" id="loaded_weight"
name="loaded_weight" min="35000" max="120000" maxlength="6" step="20"
oncopy="return false" onpaste="return false">
</div>
</fieldset>
<fieldset>
<legend class="h5 text-center text-danger">net weight</legend>
<div class="form-group">
<input type="number" class="form-control form-control-lg font-weight-bolder" id="net_weight"
name="net_weight" maxlength="5" step="20" oncopy="return false"
onpaste="return false">
</div>
</fieldset>

Create yourself a custom validation rule using:
php artisan make:rule EqualToNetWeight
That will create a new Rule class named EqualToNetWieght at app/Rules:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class EqualToNetWeight implements Rule
{
private $loadedWeight;
private $emptyWeight;
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct($loadedWeight, $emptyWeight)
{
$this->loadedWeight = $loadedWeight;
$this->emptyWeight = $emptyWeight;
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
return $value == $this->loadedWeight - $this->emptyWeight;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The net weight does not equal the loaded weight minus the empty weight.';
}
}
I've customised the messages() function to be more appropriate and descriptive for this use case.
The passes() function is where we perform the validation checking, in this case that your calculation (net weight == loaded weight - empty weight) passes and return the result (true or false) of that calculation.
The values of loaded weight and empty weight are accepted via the constructor() function.
To use the rule you would do something like:
'net_weight' => [
'required',
new EqualToNetWeight($request->loaded_weight, $request->empty_weight)
]

Related

Undefined variable when using error is coming

I have made a simple form when I am calling the form from api route it is showing an error that "errors" is an undefined variable when I am calling using web route it just works fine and shows no error. Why is this happening? Since error is a pre defined variable but why is it showing error.
Layout file:
#extends('layout')
#section('content')
<h1 class="title">Simple Form</h1>
<form method="POST" action="/website/atg/public/projects">
#csrf
<div class="field">
<label class="label" for="name">Name</label>
<div class="control">
<input type="text" class="input" name="name" placeholder="Enter Name" value="{{old('name')}}" required>
</div>
</div>
<div class="field">
<label class="label" for="email">E-mail</label>
<div class="control">
<input type="text" class="input" name="email" placeholder="Enter E-mail Address" value="{{old('email')}}" required>
</div>
</div>
<div class="field">
<label class="label" for="pincode">Pincode</label>
<div class="control">
<input type="text" class="input" name="pincode" placeholder="Enter Pincode" value="{{old('pincode')}}" required>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button">Submit</button>
</div>
</div>
#if($errors->any())
<div class="notification">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</form>
#endsection
Routes file:
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
/*Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
*/
Route::apiResource('projects','ATGController');
Controller file:
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Mail\ProjectCreated;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class ATGController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('projects.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'name'=>'required|unique:projects,name',
'email'=>'required|email|unique:projects,email',
'pincode'=>'required|digits:6'
]);
if ($validator->fails()) {
return redirect('/projects')
->withErrors($validator)
->withInput();
}
else{
$project=Project::create(request(['name','email','pincode']));
\Mail::to('sbansal1809#gmail.com')->send(
new ProjectCreated($project)
);
//echo '<script>alert("User added sucessfully!")</script>';
return response()->json($project);
}
}
/**
* Display the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
//
}
}
you have to return validator fails like this, to be able to get $errors in your blade. Check below example for reference and change the code to your parameters
don't forget to import use Illuminate\Support\Facades\Validator;
public function store(Request $request){
$validator = Validator::make($request->all(), [
'name'=>'required|unique:projects,name',
'email'=>'required|email|unique:projects,email',
'pincode'=>'required|digits:6'
]);
if ($validator->fails()) {
return redirect('/projects/create')
->withErrors($validator)
->withInput();
}else{
$project=Project::create(request(['name','email','pincode']));
\Mail::to('sbansal1809#gmail.com')->send(
new ProjectCreated($project)
);
//echo '<script>alert("User added sucessfully!")</script>';
return response()->json($project);
}
}

When i am clicking submit button it shows "object not found" error

I have made a form to submit user data but when I am clicking submit button it shows an error "Object not found"
View file`
#extends('layout')
#section('content')
<h1 class="title">Simple Form</h1>
<form method="POST" action="/projects">
#csrf
<div class="field">
<label class="label" for="name">Name</label>
<div class="control">
<input type="text" class="input" name="name" placeholder="Enter Name">
</div>
</div>
<div class="field">
<label class="label" for="email">E-mail</label>
<div class="control">
<input type="text" class="input" name="email" placeholder="Enter E-mail Address">
</div>
</div>
<div class="field">
<label class="label" for="pincode">Pincode</label>
<div class="control">
<input type="text" class="input" name="pincode" placeholder="Enter Pincode">
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button">Submit</button>
</div>
</div>
</form>
#endsection
Controller file
<?php
namespace App\Http\Controllers;
use App\Project;
use Illuminate\Http\Request;
class ATGController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('projects.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
return request()->all();
}
/**
* Display the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
//
}
}
Route file
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/projects','ATGController#index');
Route::get('/projects/create','ATGController#create');
Route::post('/projects','ATGController#store');
Layout file
<!DOCTYPE html>
<html>
<head>
<title>ATG</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.min.css">
</head>
<body>
<div class="container">
#yield('content')
</div>
</body>
</html>
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.39 (Win64) OpenSSL/1.1.1c PHP/7.3.7
You need not to use a / before a url.
web.php:
Route::post('projects','ATGController#store');
view file:
<form method="POST" action="{{ url('projects') }}">
If this does not resolve the issue kindly check your app_url in your .env file.

Laravel: create a button that affect a column in my database

Is it possible to create a button that changes a column value in a table?
I have a column named status in my movimentations table, and I was wondering if it is possible to change the value of this column with a button in my view that can change from active to inactive
this is my view
<div class="container">
<label for="name" class="form-group"><b>Nome</b>: {{ $movs->nameCoop }}</label><br>
<label for="name"><b>Numero</b>: {{ $movs->numCoop }}</label><br>
<label for="name"><b>CPF</b>: {{ $movs->cpfCoop }}</label><br>
<label for="name"><b>Cadastro</b>: {{ $movs->dtCad }}</label><br>
<label for="name"><b>Demissão</b>: {{ $movs->dtDem }}</label><br>
<label for="name"><b>Observações</b>: {{ $movs->description }}</label><br>
<label for="name"><b>Subscritas</b>: {{ $movs->subscritas }}</label><br>
<label for="name"><b>A integralizar</b>: {{ $movs->aintegralizar }}</label><br>
<label for="name"><b>Integralizadas</b>: {{ $movs->integralizadas }}</label><br>
<label for="name"><b>Status</b>: {{ $movs->status }}</label><br>
<td>
<form action="/trans" method="POST">
#csrf
<div class="input-group">
<input type="hidden" class="form-control" name="r" value={{$cooperado->id}}>
<button type="submit" class="btn btn-primary">
<span>+</span>
</button>
</span>
</div>
</form>
</td>
<td>
<form action="/mvs" method="POST">
#csrf
<div class="input-group">
<input type="hidden" class="form-control" name="v" value={{$cooperado->id}}>
<button type="submit" class="btn btn-primary">
<span>ver mvs</span>
</button>
</span>
</div>
</form>
</td>
this is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cooperado;
class CooperadoController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
//$cooperados = Cooperado::all();
$cooperados = Cooperado::orderBy('dtCad', 'desc')->paginate(10);
return view('cooperados.index', compact('cooperados'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('cooperados.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$request->validate([
'nameCoop'=>'required',
'numCoop'=> 'required|integer',
'cpfCoop'=> 'required',
'dtCad'=>'required|date',
'subscritas'=>'required'
]);
$cooperado = new Cooperado([
'nameCoop' => $request->get('nameCoop'),
'numCoop'=> $request->get('numCoop'),
'cpfCoop'=> $request->get('cpfCoop'),
'dtCad'=> $request->get('dtCad'),
'description'=> $request->get('description'),
'subscritas'=> $request->get('subscritas'),
'aintegralizar'=> $request->get('subscritas'),
'status'=> $request->get('status')
]);
$cooperado->save();
return redirect('/cooperados')->with('success', 'Cooperado adicionado');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
$cooperado = Cooperado::find($id);
return view('cooperados.show', compact('cooperado'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
$cooperado = Cooperado::find($id);
return view('cooperados.edit', compact('cooperado'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
$request->validate([
'nameCoop'=>'required',
'numCoop'=> 'required|integer',
'cpfCoop'=> 'required',
'dtCad'=>'required|date',
'subscritas'=>'required'
]);
$cooperado = Cooperado::find($id);
$cooperado->nameCoop = $request->get('nameCoop');
$cooperado->numCoop = $request->get('numCoop');
$cooperado->cpfCoop = $request->get('cpfCoop');
$cooperado->dtCad = $request->get('dtCad');
$cooperado->dtDem = $request->get('dtDem');
$cooperado->description = $request->get('description');
$cooperado->subscritas = $request->get('subscritas');
$cooperado->integralizadas = $request->get('integralizadas');
$cooperado->aintegralizar = $request->get('aintegralizar');
$cooperado->status = $request->get('status');
$cooperado->save();
return redirect('/cooperados')->with('success', 'Cooperado atualizado');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
$cooperado = Cooperado::find($id);
$cooperado->delete();
return redirect('/cooperados')->with('success', 'Sucess');
}
}
I've tried to create a function in my route, but didn't work.
I added option button for active and inactive
<form action="/active-deactive" method="POST">
#csrf
<div class="input-group">
<input type="hidden" class="form-control" name="v" value="{{$cooperado->id}}">
<select required class="form-control" id="status" name="status">
<option value="1">Active</option>
<option value="0">De-Active</option>
</select>
</div>
<button type="submit" class="btn btn-primary">
<span>Confirm</span>
</button>
</div>
</form>
controller
public function Confirm(Request $request)
{
$id = $request->input('v');
$status=$request->input('status');
DB::table('tablename')
->where('id',$id)
->update(['status'=>$status]);
}
route
Route::post('/active-deactive','YourController#Confirm')
Of course you can. You can send a request via ajax when clicking on that button:
$.ajax({
type:'POST',
url:'{{ route("NameOfYourRoute") }}',
dataType:'json',
data:{
isActive = $('#theButtonID').val(),
_token = '<?php echo csrf_token() ?>'
},
success:function(data){
if (data.updated) {
alert('Data Updated');
}
}
});
Then in your controller, you can have a function that receives the value of the button (active or inactive) and updated your table in the database:
public function toggleActivity(Request $request)
{
$isActive = $request->get('isActive');
$updated = Model::where(yourCriteria)->update(['isActive' => $isActive]);
return view('YourView', compact('updated'));
}

OCTOBERCMS Form and Model

I'm a newbie in OctoberCms and i don't have much knowledge in Laravel also. While self studying I face a request like this it's a Select if record exist query I need to read the database and look for the match and I'm really confuse.
This is my form in form.htm where I design my Form.
use Drufal\DynamicContentManager\Models\MembersVerification;
==
<form data-request="onSend" accept-charset="UTF8" enctype="multipart/form-data">
<div class="form-group">
<label>First Name:</label>
<input type="text" class="form-control" name="first_name" required>
</div>
<div class="form-group">
<label>Middle Name:</label>
<input type="text" class="form-control" name="middle_name">
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" class="form-control" name="last_name" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
and this my model
<?php namespace Drufal\DynamicContentManager\Models;
use Model;
use Input;
/**
* Model
*/
class MembersVerification extends Model
{
use \October\Rain\Database\Traits\Validation;
/*
* Disable timestamps by default.
* Remove this line if timestamps are defined in the database table.
*/
public $timestamps = false;
/**
* #var array Validation rules
*/
public $rules = [
];
/**
* #var string The database table used by the model.
*/
public $table = 'drufal_dynamiccontentmanager_members';
public function onSend(){
$fn = Input::get('first_name');
$mn = Input::get('middle_name');
$ln = Input::get('last_name');
$membertbl=$table::where('first_name', '=', $fn)->first();
if ($membertbl === null) {
echo"
<script>
alert('Successfully');
</script>
";
}else{
echo"NO RESULT";
}
}
}
Help the newbie please.
I think you missed the DB:: in your database request:
$users = Db::table('users')->where('votes', 100)->first();
Maybe this documentation will help you:
https://octobercms.com/docs/database/query#where-clauses

Form array validation Laravel 5.2

I am currently stuck on solving this problem. I am new to Laravel and the MVC framework. I am struggling to create the dynamic form that gives the user the ability to add as many forms as possible. When the user enters the page at first it generates 5 form fields . Here is a look at my code so far.
<div id ={{$id = "from".$i}} >
<div class="form-group col-md-6">
<div class="col-md-6 form-group">
<label for={{$id = "Address".$i}}>Address</label>
<input type="text" name = "address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address"> <!-- problem form array how does this work in laravel -->
</div>
<div class="form-group col-md-6">
<label for={{$id = "city".$i}}>City</label>
<input type="text" value = "{{ old('city') }}" class="form-control" id={{$id = "City".$i}} placeholder="City">
#if ($errors->has('city'))
<span class="help-block">
<strong>{{ $errors->first('city') }}</strong>
</span>
#endif
</div>
How would I go about validating a form in Laravel 5.2 with from array
here's my controller
public function Postdata(Request $request) {
$this->validate($request->all(), [
'address.*' => 'required|string',
'city' => 'required',
]);
}
I am using a for loop to generate the forms dynamically.
here is the error I get
ErrorException in ValidatesRequests.php line 49:
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given, called in
C:\wamp\www\Dynamic- 1.0\app\Http\Controllers\propContoller.php on line 34 and defined
Can someone please help or point me in the right direction thank you !
add name="city[{{$i}}]"
Create a specific request with php artisan make:request PostRequest
Change public function Postdata(Request $request) { to public function Postdata(PostRequest $request) {
Remove the validate function call from your controller
Go to /app/Http/Requests/PostRequest.php
Then edit the rules function to something like this ...
.
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [];
foreach($this->request->get() as $key => $val)
{
$rules['address.' . $key] = 'required';
$rules['city.' . $key] = 'required';
}
return $rules;
}
Thank You man ! this is the solution I end up with
<div class="form-group col-md-6">
<div class="col-md-6 form-group">
<label for={{$id = "Address".$i}}>Address</label>
<input type="text" name="address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address">
</div>
in post request i did this
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules() {
$rules = [];
foreach($this->request->get('address') as $key => $val) {
$rules['address.'.$key] = 'required';
}
return $rules;
}

Categories