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
Related
How to upload a file and save it in Prestashop 1.7?
In ProductComments module I have a modal with a <form>:
post-comment-modal.tpl
<form id="post-product-comment-form" action="{$post_comment_url nofilter}" method="POST" enctype="multipart/form-data">
<div>
<div class="form-floating">
<input name="comment_title" type="text" class="form-control" placeholder="Title"/>
<label for="comment_title">Title</label>
</div>
<div class="form-floating">
<input name="customer_name" type="text" class="form-control" placeholder="Name"/>
<label for="customer_name">Name</label>
</div>
<div class="form-floating">
<textarea name="comment_content" class="form-control" placeholder="Review"></textarea>
<label for="comment_content">Review</label>
</div>
<input type="file" id="photo_input" name="photo_input" multiple> // I've added this field
<button type="submit">Send</button>
</div>
</form>
I've added there a <input type="file">.
This form is posted into ProductCommentsPostCommentModuleFrontController which extends ModuleFrontController
PostComment.php
class ProductCommentsPostCommentModuleFrontController extends ModuleFrontController
{
public function display()
{
$id_product = (int) Tools::getValue('id_product');
$comment_title = Tools::getValue('comment_title'); // Proper value
$comment_content = Tools::getValue('comment_content'); // Proper value
$customer_name = Tools::getValue('customer_name'); // Proper value
$criterions = (array) Tools::getValue('criterion');
$photo = Tools::getValue('photo_input'); // false
$file = $_FILES['photo_input']['name']; // null
// Validation
/** #var EntityManagerInterface $entityManager */
$entityManager = $this->container->get('doctrine.orm.entity_manager');
//Create product comment
$productComment = new ProductComment();
// Validation
$productComment
->setProductId($id_product)
->setTitle($comment_title)
->setContent($comment_content)
->setCustomerName($customer_name)
->setCustomerId($this->context->cookie->id_customer)
->setGuestId($this->context->cookie->id_guest)
->setDateAdd(new \DateTime('now', new \DateTimeZone('UTC')))
;
$entityManager->persist($productComment);
$this->addCommentGrades($productComment, $criterions);
$entityManager->flush();
$this->ajaxRender(
json_encode(
[
'success' => true,
'product_comment' => $productComment->toArray(),
]
)
);
}
Is there a way to extend this controller, and add a variable which holds a file upoaded by user by POST method?
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)
]
Hi i tried everything i found on Google but nothing work, i have always the error trailing data when i'm trying to insert date in my db. i Hope someone can help me. Thanks a lot and sorry for my english.
//here's my model location
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Location extends Model
{
protected $table = 'location';
}
//Heres's My migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Location extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('location', function(Blueprint $table) {
$table->bigIncrements('id');
$table->date('start');
$table->date('end');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('location');
}
}
//And here's my method to store date in my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Location;
use Carbon\Carbon ;
public function storeDate(Request $request){
$location = new Location();
$start = Carbon::createFromFormat('m/d/y', $request->input("start"));
$end = Carbon::createFromFormat('m/d/y', $request->input("end"));
$location->start = $start;
$location->end = $end;
$location->save();
return redirect('/myCar');
}
}
My form
<form class="form-inline" method="POST" action="/storedate">
#csrf
<div class="modal-body">
<label class="sr-only" for="inlineFormInputName2"></label>
<input type="text" class="form-control mb-2 mr-sm-2" id="inlineFormInputName2" placeholder="dd/mm/yyyy" value="20/04/2019" name="start">
<label class="sr-only" for="inlineFormInputGroupUsername2"></label>
<div class="input-group mb-2 mr-sm-2">
<input type="text" class="form-control" id="inlineFormInputGroupUsername2" placeholder="dd/mm/yyyy" value="20/04/2019" name="end">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Send message</button>
</div>
</form>
It's ok i found it. In m/d/y my y need to be in uppercase :
m/d/Y
Thank you for your support !
I am using PHP Laravel framework. I am trying to save a form after submission. Strangely first time it is not saving, but subsequently, it is saving. On the first post request, the flow isn't even entering function save_application
Code below.
My controller:
class ApplicationController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth',['except' => ['store_application']]);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function save_application(Request $request){
$user = Auth::user();
if(isset($request->application)){
$application = Application::where("user_id",$user->id)->first();
if($application){
$application->update($request->application);
}else{
$application = new Application;
$application = Application::create($request->application);
$application->user_id = $user->id;
$application->save();
}
}
return $this->store_application($request);
}
public function store_application(Request $request){
if(isset($request->application)){
if($request->session()->has('application')){
$request->session()->forget('application');
}
$application_data = [];
$application = new Application;
$application->attributes = $request->application;
$application_data["application"] = $application;
$request->session()->put("application" , $application_data);
}
//
return Redirect::to("/application")->withErrors(array("success"=>"Thank you for submitting the application"));
}
}
My routers
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('application');
My html
<form method="POST" action="/application" enctype="multipart/form-data" id='application_form'>
<input type="hidden" name="_token" value="xtQapusSjgf5XVUxjCOudedeH93a8hEqyfaNh8ChEaKt">
<input type='checkbox'>
<label>I've read and accept the terms and conditions</label>
<p class='font-size-16 font-bold text-uppercase text-black'>
Your information
</p>
<hr class='hr1'>
<div class='row form-group'>
<div class='col-lg-6'>
<label class='control-label'>First name*</label>
<input type='text' class='form-control' name='application[first_name]' value="">
</div>
<div class='col-lg-6'>
<label class='control-label' >Last name*</label>
<input type='text' class='form-control' name='application[last_name]' value="">
</div>
</div>
<div class='form-group'>
<label class='control-label' >Middle name</label>
<input type='text' class='form-control' name='application[middle_name]' value="">
</div>
<div class='form-group'>
<label class='control-label'>ID*</label>
<input type='text' class='form-control' name='application[]' value="">
</div>
<button class="btn btn-primary text-uppercase">Submit <i class='fa fa-check text-white'></i></button>
</form>
your routes have the same name, give them differents.
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('other');
and in your form, you can:
<form method="POST" action="{{ route('application') }}" enctype="multipart/form-data" id='application_form'>
and as senty say:
<button type="submit">
</form>
I think you overcomplicate things, you can simply use updateOrCreate() to make it cleaner.
First of all, make sure $fillable or $guarded is utilized in your Application model. (Application.php)
protected $fillable = ['each', 'field', 'as', 'string'];
// or
protected $guarded = [];
Some improvements for your method:
public function save_application(Request $request){
// 1. Do a proper check
$request->validate([
'application.first_name' => 'required',
'application.middle_name' => 'required',
'application.last_name' => 'required'
]);
// 2. Update or Create
$application->updateOrCreate(
[ 'user_id' => $user->id ],
$request->application // I suppose this is an array that you want
);
// 3. Handle the redirect the right way so you can eliminate the other `store_applcation()` method entirely
return redirect()->back()->with([
'application' => $application
'success' => "Your Message"
]);
}
Also you don't need store_application() method in your controller or its route because your html form is POST'ing to /application route.
This is what you want, right?
I have created a test user on my laravel app. The details are
user: joe#gmail.com pass: 123456
When I go through the registration process everything works as expected and an entry is made into the users table of the database
Once this is finished I redirect the user to the dashboard.
public function postCreate(){
//Rules
$rules = array(
'fname'=>'required|alpha|min:2',
'lname'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->passes()){
//Save in DB - Success
$user = new User;
$user->fname = Input::get('fname'); //Get the details of form
$user->lname = Input::get('lname');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));//Encrypt the password
$user->save();
return Redirect::to('/books')->with('Thank you for Registering!');
}else{
//Display error - Failed
return Redirect::to('/')->with('message', 'The Following Errors occurred')->withErrors($validator)->withInput();
}
}
I then navigate back to the landing page and attempt to log in using the credentials above and I keep getting told that Auth::attempt() is failing hence my user cannot log into the application.
public function login(){
if(Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))){
//Login Success
echo "Success"; die();
return Redirect::to('/books');
}else{
//Login failed
echo "Fail"; die();
return Redirect::to('/')->with('message', 'Your username/password combination was incorrect')->withInput();
}
}
Does anyone know why this is happening? This is the Schema for my users table:
Schema::create('users', function($table){
$table->increments('id');
$table->integer('type')->unsigned();
$table->string('fname', 255);
$table->string('lname', 255);
$table->string('email')->unique();
$table->string('password', 60);
$table->string('school', 255);
$table->string('address_1', 255);
$table->string('address_2', 255);
$table->string('address_3', 255);
$table->string('address_4', 255);
$table->string('remember_token', 100);
$table->timestamps();
});
Any help is much appreciated.
'View for Login':
<div class="page-header">
<h1>Home page</h1>
</div>
<!-- Register Form -->
<form action="{{ action('UsersController#postCreate') }}" method="post" role="form">
<h2 class="form-signup-heading">Register</h2>
<!-- Display Errors -->
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<!-- First Name -->
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" name="fname" />
</div>
<!-- Last Name -->
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" name="lname" />
</div>
<!-- Email -->
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<!-- Password-->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<!-- Confirm Password -->
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" name="password_confirmation" />
</div>
<input type="submit" value="Register" class="btn btn-primary"/>
</form>
<!-- Login Form -->
<form action="{{ action('UsersController#login') }}" method="post" role="form">
<h2 class="form-signup-heading">Login</h2>
<!-- Email -->
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<!-- Password-->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<input type="submit" value="Login" class="btn btn-primary"/>
</form>
Can you run this function below - and tell me where the error occurs? It will diagnose the problem:
public function testLogin()
{
$user = new User;
$user->fname = 'joe';
$user->lname = 'joe';
$user->email = 'joe#gmail.com';
$user->password = Hash::make('123456');
if ( ! ($user->save()))
{
dd('user is not being saved to database properly - this is the problem');
}
if ( ! (Hash::check('123456', Hash::make('123456'))))
{
dd('hashing of password is not working correctly - this is the problem');
}
if ( ! (Auth::attempt(array('email' => 'joe#gmail.com', 'password' => '123456'))))
{
dd('storage of user password is not working correctly - this is the problem');
}
else
{
dd('everything is working when the correct data is supplied - so the problem is related to your forms and the data being passed to the function');
}
}
Edit: one thought - are you sure the user is being correctly saved in the database? Have you tried to 'empty/delete' your database and try your code again? In your current code, it will fail if you keep registering with joe#gmail.com - because it is unique. But you dont catch the error anywhere. So empty the database and try again...
Edit 2: I found another question you posted with the same problem - and in there you mentioned that the following code is your user model?
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
public function getAuthIdentifier() {
}
public function getAuthPassword() {
}
public function getRememberToken() {
}
public function getRememberTokenName() {
}
public function getReminderEmail() {
}
public function setRememberToken($value) {
}
}
Is that EXACTLY your current user model? Because if so - it is wrong - none of those functions should be blank.
This is what a CORRECT user model should look like for Laravel 4.2
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
You would make sure about:
your model:
mine looks like:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password');
public function getAuthIdentifier()
{
Return $this->getKey ();
}
public function getAuthPassword()
{
return $this->password;
}
}
make sure your app/config/auth.php is configured correctly
make sure app/config/app.php has service provider
'Illuminate\Auth\AuthServiceProvider',
Make sure your controller class has auth. before writing class you have used Auth (I mean include Auth class)
That all could make Auth doesn't work well
With password hashing enabled, the User model must override these methods:
public function getAuthIdentifierName()
{
return 'email';
}
public function getAuthIdentifier()
{
return request()->get('email');
}
public function getAuthPassword()
{
return Hash::make(request()->get('password'));
}
What is the value for strlen(Hash::make(Input::get('password')))? If it is greater than 60, then this would cause the authentication to fail each time, as the stored password is not the full hash.
Good day, here is what I discovered when I encountered the same error: A simple string compare will reveal that the two hashing methods produce two different hashed values.
echo strcmp(Hash::make('password'),bcrypt('password'));
My assumption is that Auth::attempt([]) uses bcrypt() to hash out passwords which produces a different value to what you used Hash:make().