I am very new to Laravel, and our system uses multiple forms within a single page to insert the single bitcoin wallet into each input field, but as it stands the user is able to use it on all inputs and this is wrong as could i make only one valid? such as "username" "email" etc ..
html:
<form method="POST" action="/wallet3-edit/update">
<div class="form-group hidden">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="PATCH">
</div>
<div class="form-group {{ $errors->has('bitzpayer_id3') ? ' has-error' : '' }}">
<label for="bitzpayer_id3" class="control-label"><b>Wallet:</b></label>
<input type="text" name="bitzpayer_id3" placeholder="Please enter your Wallet here" class="form-control" value="{{ $user->bitzpayer_id3 }}"/>
<?php if ($errors->has('bitzpayer_id3')) :?>
<span class="help-block">
<strong>{{$errors->first('bitzpayer_id3')}}</strong>
</span>
<?php endif;?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-warning text-white"> Submit </button>
</div>
</form>
Controller:
<?php
namespace App\Http\Controllers;
use Auth;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class Wallet3Controller extends Controller
{
/**
* Update user profile & make backend push to DB
*
**/
public function index() {
/**
* fetching the user model
**/
$user = Auth::user();
//var_dump($user);
/**
* Passing the user data to profile view
*/
return view('/wallet3-edit', compact('user'));
}
public function update(Request $request) {
/**
* fetching the user model
*/
$user = Auth::user();
/**
* Validate request/input
**/
$this->validate($request, [
'bitzpayer_id3' => 'max:255|unique:users,bitzpayer_id3,'.$user->id,
]);
/**
* storing the input fields name & email in variable $input
* type array
**/
$input = $request->only('bitzpayer_id3');
/**
* Accessing the update method and passing in $input array of data
**/
$user->update($input);
/**
* after everything is done return them pack to /profile/ uri
**/
return back();
}
}
Routes:
Route::get('wallet3-edit', 'Wallet3Controller#index');
Route::patch('wallet3-edit/{id}', 'Wallet3Controller#update');
if you want to validate not duplication in a single page:
because The page dosent send any request to server until the form completes,
you can check this within javascript/jquery like this:
$(".inputs").change(function(){
if($("#input1").val()==$("#input2").val()){
$("#input1").addClass("error");
}
});
but if your input are seprated in different pages and save in database you can validate with them with this kind of rules in Laravel controller or Laravel Request Class:
$validationRules = ["wallet" => "required|unique:wallets_table,btc"];
where "wallet" is the name of your input field. "wallets_table" is your database table and "btc" is table column.
but if you are not willing to save the wallet public keys in Database and the requests are from a single user, you can save the "Address"es in a Session Array and check them out when a user submit a request. but this solution works User Scope .
please give me more details if I misunderstood.
Related
Hello i'm new in laravel. My application has a search bar component in almost every view.
The user types there the ID of the client, makes a query to db and compares the user's typed ID with the DB client ID.
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class SearchController extends Controller
{
function get_kcli(Request $request) {
$id = $request->input('kcli');
$current_page = $request->input('currentPage') . '.index';
$data = DB::connection('oracle')->table('CLIENTS')->where('KCLI', $id)->get();
return view($current_page, compact('data'));
}
}
Web.php
Route::post('/search', [App\Http\Controllers\SearchController::class, 'get_kcli'])->name('search');
Form search component view:
<nav class="navbar navbar-light">
<form method="POST" class="form-inline position-relative" action="{{ route('/search') }}">
#csrf
#method('POST')
<input class="form-control shadow-none" name="kcli" id="kcli" type="number" placeholder="Codice..." aria-label="Search">
<input type="text" name="currentPage" value="{{ Route::currentRouteName() }}" hidden>
<button type="submit" class="btn btn-light search-btn"><i class="fas fa-search"></i></button>
</form>
Anyone knows the best practice to store that data request globally an mantain it for every view that need to exctract it?
Example : I search for the client ID '5', the search controller makes a db query with the passed ID, then compacts data. That data has to be stored globally for get the results and post it in other views, without searching again on every view switch(the typed ID '5' has to remain in the search field on every view switch).
To print client_id you can store that "id" in session and print from the session by this way your search value keep remains and to get data in all views there is the concept View::share you can register that in AppServiceProvider please go through this link
https://laravel.com/docs/9.x/views#sharing-data-with-all-views
My form:
<form action="{{route('settings.update')}}" method="POST">
#csrf
<div class="col-sm-3">
<div class="form-group">
<label for="avatar">Upload a new one:</label>
<input type="file" id="pic" name="pic"/>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Upload avatar</button>
</div>
</form>
My Controller:
public function update_settings($request)
{
$this->validate($request, [
'pic' => 'required|image'
]);
$path = $request->image->store('/img/');
Auth::user()->image = $path;
return view('pages.settings');
}
The error:
Too few arguments to function App\Http\Controllers\PagesController::update_settings(), 0 passed and exactly 1 expected
I am passing only the image file in the $request, but for some reason the controller doesn't see it, what am I doing incorrectly?
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller constructor or method. The current request instance will automatically be injected by the service container:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class UserController extends Controller
{
/**
* Store a new user.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$name = $request->input('name');
//
}
}
Look well that in the method I am injecting the dependence of Illuminate\Http\Request
You need to add enctype='multipart/form-data' to your opening form tag
<form action="{{route('settings.update')}}" method="POST" enctype="multipart/form-data">
At the moment I am working with Laravel. I am trying to insert data into a database. It is not user data, but product data. Costumers have to be able to insert a title, description and price of a product into the database.
I have looked at the laravel website, however, I was unable to find anything. There are some people with the same question as mine on StackOverflow. However, the answers that were given to them do not work for me.
My controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data=array('title'=>$productname,"description"=>$description,"price"=>$price);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
My view:
#section('content')
<h1>Add your new items here:</h1>
<form method="get">
<div class="title">
<div class="title">
<span class="input-group-text" id="title">Title</span>
</div>
<input type="text" name="title" class="form-control" aria-label="title" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="description">
<div class="description">
<span class="input-group-text" id="description">Description</span>
</div>
<input type="text" name="description" class="form-control" aria-label="description" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="price">
<div class="price">
<span class="input-group-text" id="price">Price</span>
</div>
<input type="text" name="price" class="form-control" aria-label="price" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="form-group">
<label for="exampleFormControlFile1">Insert Image</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
My web.php:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('insert','ProductsController#insertform');
Route::post('create','ProductsController#insert');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
My database structure:
The home and welcome, along with some code in the web.php, has been made by authentication.
Hopefuly you guys can help me out. I want to make sure that the product data is inserted into the database.
Don't use DB class. Instead create a model called Product and use model function to create or update data into table.
php artisan make:model Product
$product= Product::create([
'name' => $request->name, # declared as fillable on Product model
'description' => $request->description,
...
]);
Convert the route of /insert into POST and add csrf field in your form
#csrf
OR
<input type="hidden" name="_token" value="{{csrf_token()}}">
On your controller validation of input in insert function.
Also take a look at these -
https://laravel.com/docs/5.8/eloquent#defining-models
Laravel Validation Rules
or https://laravel.com/docs/5.8/validation#quick-writing-the-validation-logic
In your web.php, Add route names
Route::get('insert','ProductsController#insertform')->name('product.create');
Route::post('create','ProductsController#insert')->name('product.store');
In your view, change method to post and add action attribute and csrf field.
<form action="{{ route('product.store') }}" method="post">
#csrf
In Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data = array(
"title" => $productname,
"description" => $description,
"price" => $price
);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
Alternate you can directly add action without route name
<form action="/create" method="post">
#csrf
In laravel 5.6 i can show you how to insert the data and display the data to the index page
so first of all i can code my route
in here we can use 2 routes
first is index page route
second is store and in store controller you can display your stored data.
Route::get('/FAQ_page', 'SettingController#FAQ_page')->name('FAQ_page');
Route::get('/FAQ_page/create', 'SettingController#FAQ_page_create')->name('FAQ_page.create');
Route::post('/FAQ_page/store', 'SettingController#FAQ_pagestore');
now make a database and connect to your module
this is your module
namespace App;
use Illuminate\Database\Eloquent\Model;
class FAQpage extends Model
{
protected $table = 'p66_FAQ_page';
public $timestamps = false;
protected $primaryKey = 'fid';
}
now make your controller like this
public function FAQ_page()
{
$data = FAQpage::get();
return view('SuperAdmin.settings.FAQ_page', compact('data'));
}
public function FAQ_page_create()
{
return view('SuperAdmin.settings.FAQ_page_create');
}
public function FAQ_pagestore(Request $request)
{
request()->validate([
'FAQ_question'=> 'required',
'FAQ_answer'=> 'required',
'Sort_order'=> 'required|max:4',
'FAQ_departments'=> 'required',
]);
$data = new FAQpage();
$data->FAQ_question = $request->get('FAQ_question');
$data->FAQ_answer = $request->get('FAQ_answer');
$data->Sort_order = $request->get('Sort_order');
$data->FAQ_departments = $request->get('FAQ_departments');
$data->Created_date = Carbon::now();
$data->save();
return redirect('/SuperAdmin/FAQ_page');
}
thank you
Whenever a user goes to mywebsite.com/profile I want a form to pre populate the values they've entered during the signup/registration flow. I was able to do that with my form here
<h1><b>Your Profile</b></h1>
<form method="POST" action="/profile/update">
<div class="form-group hidden">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="PATCH">
</div>
<div class="form-group {{ $errors->has('name') ? ' has-error' : '' }}">
<label for="email" class="control-label"><b>Name:</b></label>
<input type="text" name="name" placeholder="Please enter your email here" class="form-control" value="{{ $user->name }}"/>
<?php if ($errors->has('name')) :?>
<span class="help-block">
<strong>{{$errors->first('name')}}</strong>
</span>
<?php endif;?>
</div>
<div class="form-group {{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="control-label"><b>Email:</b></label>
<input type="text" name="email" placeholder="Please enter your email here" class="form-control" value="{{ $user->email }}"/>
<?php if ($errors->has('email')) :?>
<span class="help-block">
<strong>{{$errors->first('email')}}</strong>
</span>
<?php endif;?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default"> Submit </button>
</div>
</form>
But now im running into the issue if the user just hits submit button without changing any fields, laravel's built in validations checks and gives me an error message of The name has already been taken. which is true. so im not sure how to handle this issue, but here is my controller below
<?php
namespace App\Http\Controllers;
use Auth;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ProfileController extends Controller
{
/**
* Update user profile & make backend push to DB
*
**/
public function index() {
/**
* fetching the user model
**/
$user = Auth::user();
//var_dump($user);
/**
* Passing the user data to profile view
*/
return view('profile', compact('user'));
}
public function update(Request $request) {
/**
* Validate request/input
**/
$this->validate($request, [
'name' => 'required|max:255|unique:users',
'email' => 'required|email|max:255|unique:users',
]);
/**
* storing the input fields name & email in variable $input
* type array
**/
$input = $request->only('name','email');
/**
* fetching the user model
*/
$user = Auth::user();
/**
* Accessing the update method and passing in $input array of data
**/
$user->update($input);
/**
* after everything is done return them pack to /profile/ uri
**/
return back();
}
}
and here is my routes file.
// only authenticated users
Route::group( ['middleware' => 'auth'], function() {
Route::get('/home', 'HomeController#index');
// practicing using forms for sending data to the DB & populating form fields with DB data
Route::get('profile', 'ProfileController#index');
Route::patch('profile/{id}', 'ProfileController#update');
});
Issue is due to unique validation rule. You can exclude the current user id by specifying unique validation rule. your code will be like this
public function update(Request $request) {
/**
* fetching the user model
*/
$user = Auth::user();
/**
* Validate request/input
**/
$this->validate($request, [
'name' => 'required|max:255|unique:users,name,'.$user->id,
'email' => 'required|email|max:255|unique:users,email,'.$user->id,
]);
/**
* storing the input fields name & email in variable $input
* type array
**/
$input = $request->only('name','email');
/**
* Accessing the update method and passing in $input array of data
**/
$user->update($input);
/**
* after everything is done return them pack to /profile/ uri
**/
return back();
}
here is laravel documentation link for this https://laravel.com/docs/5.1/validation#rule-unique
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().