The data that except in the store function does not go to the db - laravel

i'm learning laravel.
I have to do a simple store function to create a new post. The form appears to work correctly but the data does not reach the DB.
There's my store function:
public function store(Request $request)
{
$request->validate($this->validationRules);
$formData = $request->all();
$puzzle = new Puzzle();
$puzzle->fill($formData);
$puzzle->save();
// $newPuzzle = Puzzle::create($formData);
// return redirect()->route('puzzles.show', $newPuzzle->id);
}
My model:
class Puzzle extends Model
{
public $timestamps = false;
protected $fillable = [
'title',
'pieces',
'image',
'description',
'brand',
'price',
'available',
'quantity',
];
}
My form:
<form method="POST" action="{{route('puzzles.store')}}">
#csrf
<div class="mb-3">
<label for="title" class="form-label">Title</label>
<input type="text" class="form-control" id="title" name="title" value="{{ old('title') }}">
</div>
<div class="mb-3">
<label for="pieces" class="form-label">Pieces</label>
<input type="number" class="form-control" id="pieces" name="pieces" value="{{ old('pieces')}}">
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<input type="text" class="form-control" id="description" name="description" value="{{ old('description')}}">
</div>
<div class="mb-3 form-check">
<label class="form-check-label" for="available">Available</label>
<input type="checkbox" class="form-check-input" id="available" name="available" checked>
</div>
<div class="col-md-4">
<label for="quantity" class="form-label">Quantity</label>
<input type="number" min="1" step="any" class="form-control" id="quantity" name="quantity">
</div>
<div class="col-md-4">
<label for="price" class="form-label">Price</label>
<input type="number" min="3.0" step="0.1" class="form-control" id="price" name="price">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
what am I doing wrong?
Thank you

Make changes in your store function as per below
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'min:5|max:250',
'pieces' => 'numeric',
'description' => 'min:5|max:500',
'price' => 'numeric',
'available' => 'boolean',
'quantity' => 'numeric',
]);
$puzzle = Puzzle::create($request->only(
'title', 'pieces', 'description', 'available', 'quantity', 'price'
));
return redirect()->route('puzzles.show', $puzzle->id);
}
in .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_databse_name
DB_USERNAME=your_databse_user_name
DB_PASSWORD=your_databse_password

Related

Where do I add custom verification for user registration

I have a custom regitration form where I need (users telephone number and company id) as well as email and password.
The telephone number and company id will get an api call to verify its existence in the comapny directory. If it passes then I need to allow User model to make the registration but if it fails then return a fail.
Q: where in the chain of registration should I make this api call to allow/reject the registration?
my \resources\views\auth\register.blade.php looks like this
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<label for="companyid" class="col-md-4 col-form-label text-md-right">Innovations ID</label>
<div class="col-md-6">
<input id="companyid" type="text" class="form-control" name="companyid" value="" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="telephonenumber" class="col-md-4 col-form-label text-md-right">Zip Code</label>
<div class="col-md-6">
<input id="telephonenumber" type="text" class="form-control" name="telephonenumber" value="" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
here is my controller app\Http\Controllers\Auth\RegisterController.php
I would think this is where I would add my api call but not sure how to go about it.
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct(){
$this->middleware('guest');
}
protected function validator(array $data){
return Validator::make($data, [
'companyid' => ['required', 'string', 'max:255'],
'telephonenumber' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'companyid' => $data['companyid'],
'telephonenumber' => $data['telephonenumber'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
this is my user model app\User.php
protected $fillable = [
'companyid', 'telephonenumber', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
You need to do it in the create method of the RegisterController.
You can make api calls within create method using the Http facade. But you need to have guzzle as dependency in your project. You can pull it using composer.
composer require guzzlehttp/guzzle
Then you can make the api calls
protected function create(array $data)
{
//Remember to import the use statement
//use Illuminate\Support\Facades\Http; at top
$response = Http::get('http::/example.com');
//Need to stop further execution by throwing an exception
//If the verification via api call fails
//abort_unless($response->verified = true, 419);
return User::create([
'companyid' => $data['companyid'],
'telephonenumber' => $data['telephonenumber'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Laravel docs: https://laravel.com/docs/8.x/http-client#making-requests

Trying to Register Multiple user via Default laravel Auth

I have 3 users
Customer
Restaurant
Rider
Am trying to register the rider via default routes so I can login again:
<form method="POST" action="{{ route('register') }}">
#csrf
<h4 class="text-light-black fw-600">Create your account</h4>
<input type="text" name="type" value="rider">
<div class="row">
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="form-group">
<label class="text-light-white fs-14">First name</label>
<input type="text" name="first_name" class="form-control form-control-submit"
placeholder="First Name" required>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="form-group">
<label class="text-light-white fs-14">Last name</label>
<input type="text" name="last_name" class="form-control form-control-submit" placeholder="Last Name"
required>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="form-group">
<label class="text-light-white fs-14">Username</label>
<input type="text" name="username" class="form-control form-control-submit" placeholder="Username"
required>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="form-group">
<label class="text-light-white fs-14">CNIC</label>
<input type="text" name="cnic" class="form-control form-control-submit" placeholder="CNIC" required>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="form-group">
<label class="text-light-white fs-14">Ride Number</label>
<input type="text" name="ride_number" class="form-control form-control-submit"
placeholder="Ride Number" required>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="form-group">
<label class="text-light-white fs-14">Ride Chassis</label>
<input type="text" name="chassis_number" class="form-control form-control-submit"
placeholder="Ride Chassis" required>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="form-group">
<label class="text-light-white fs-14">Password</label>
<input type="password" name="password" class="form-control form-control-submit"
placeholder="Password" required>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="form-group">
<label class="text-light-white fs-14">Confirm Password</label>
<input type="password" name="password_confirmation" class="form-control form-control-submit"
placeholder="Confirm Password" required>
</div>
</div>
<div class="col-12">
<div class="form-group">
<label class="text-light-white fs-14">Email</label>
<input type="email" name="email" class="form-control form-control-submit" placeholder="Email I'd" required>
</div>
<div class="form-group">
<label class="text-light-white fs-14">Address</label>
<input type="text" name="address" class="form-control form-control-submit" placeholder="Address" required>
</div>
<div class="form-group">
<button type="submit" class="btn-second btn-submit full-width">Create your account</button>
</div>
<div class="form-group text-center"></div>
<span class="text-light-black fs-12 terms">By creating your Munchbox account, you agree to the Terms of Use and Privacy Policy.</span>
</div>
</div>
</form>
Here's is my the create method
protected function create(array $data)
{
dd($data);
if ($data['type']=='rider')
{
$user= Rider::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'password' => Hash::make($data['password']),
'address' => $data['address'],
]);
}else
{
$user = User::create([
'name' => $data['name'],
'password' => Hash::make($data['password']),
'email' => $data['email'],
]);
}
return $user;
}
what am trying to do is when a new rider wants to register themself he can, so he can also use the default login laravel routes and methods
but am failed to do that the page refresh on the same page and the rider doesn't register in the rider table.
https://pusher.com/tutorials/multiple-authentication-guards-laravel
example:
// app/Rider.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Rider extends Authenticatable
{
use Notifiable;
protected $guard = 'rider';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
// app/Restaurant.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Restaurant extends Authenticatable
{
use Notifiable;
protected $guard = 'restaurant';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
you have to declare your guards
// config/auth.php
<?php
[...]
'guards' => [
[...]
'rider' => [
'driver' => 'session',
'provider' => 'riders',
],
'restaurant' => [
'driver' => 'session',
'provider' => 'restaurants',
],
],
[...]
and declare your providers
// config/auth.php
[...]
'providers' => [
[...]
'restaurants' => [
'driver' => 'eloquent',
'model' => App\Restaurant::class,
],
'riders' => [
'driver' => 'eloquent',
'model' => App\Rider::class,
],
],
[...]

Laravel, adding data to database after verifying ReCaptcha

I'm using ReCaptcha in my Laravel project, done it with this
tutorial.
I need to create a page where user can post his message after checking captcha.
I have created a modal dialog where user can fill in data like this :
<form class="form-horizontal" action="" method="post">
<div class="form-group error">
<label for="messageName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Your name" value=""
ng-model="message.name" ng-required="true">
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control has-error" id="email" name="email" placeholder="E-mail" value=""
ng-model="message.email" ng-required="true">
<span class="help-inline"
ng-show="GBM.email.$invalid && GBM.email.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageLink" class="col-sm-3 control-label">Web</label>
<div class="col-sm-9">
<input class="form-control" rows="3" class="form-control has-error" id="web" name="web" placeholder="Link for your web" value="" ng-model="message.web" ng-required="false" >
</div>
</div>
<div class="form-group error">
<label for="messageText" class="col-sm-3 control-label">Comment</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" class="form-control has-error" id="comment" name="comment" placeholder="Your comment" value="" ng-model="message.text" ng-required="true" ></textarea>
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
{!! csrf_field() !!}
<!-- recaptcha -->
{{Request::is('contactd')}}
<div class="form-group">
<div class="col-md-9">
<div class="g-recaptcha" data-sitekey="{{env('GOOGLE_RECAPTCHA_KEY')}}"></div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-9 control-label"></label>
<div class="col-md-9">
<button type="submit" name="send" class="btn btn-primary btn-lg btn-block">Add new message <span class="fa fa-paper-plane-o"></span></button>
</div>
</div>
</form>
For a route I got it like this:Route::post('contact','ContactController#store');
And here is the problem, in my controller i got this code to verify captcha:
public function store(ReCaptchataTestFormRequest $request){
return "Captcha done right! ";}
And this code to save data to database
public function store(Request $request)
{
$this->validate($request, [ 'name' => 'required|max:255' ]);
$this->validate($request, [ 'email' => 'required | email' ]);
$this->validate($request, [ 'comment' => 'required' ]);
$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$guestbook = Guest_books::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'web' => $request->input('web'),
'comment' => $request->input('comment'),
'ip' => $ip,
'browser' => $browser
]);
return $guestbook;
}
So the question is: What to write in Controller for project to verify Captcha and then post it to database?
The tutorial you've followed teaches you how to create a custom validation rule which you can then use when validating requests, either through a Form Request or directly in your controller.
The mistake you've made in your controller is that you've called validate multiple times, instead you should pass it an array containing all of your rules, including your recaptcha rule, e.g:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'comment' => 'required',
'g-recaptcha-response' => 'required|recaptcha',
]);
// ...
}
Additionally, you should note that the store method should always return a redirect.

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code?

How to Manage Accounts in the Laravel 5 FrameWork - MVC - with this code? I got it all for a default presentation but i still get an Undefined Variable request with this code - please your answer will be appreciated:
UserController:
public function account(&$data, $request){
User::get_user(self::$data,$request);
self::$data['title'] = self::$data['title'] . 'Edit Account';
return view('forms.account', self::$data);
}
public function postAccount(AccountRequest $request){
User::edit_user($request);
return redirect('');
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
Model:
static public function get_user(&$data,$request){
$sql = "SELECT * FROM users WHERE id = ". Session::get('user_id');
$data['users'] = DB::select($sql);
}
static public function edit_user(&$data,$request) {
$id = $data['id'];
$sql = "SELECT * FROM users WHERE id = ".$id;
$getVal = DB::select($sql);
if($data['name'] || $data['password'] || $data['email']){
if($data['name']){
DB::update("UPDATE users SET name = ? WHERE id = ?",[$data['name'],$id]);
session(['user_name' => $data['name']]);
}
if($data['password']){
DB::update("UPDATE users SET password = ? WHERE id = ?",[bcrypt($data['password']),$id]);
}
if($data['email']){
DB::update("UPDATE users SET email = ? WHERE id = ?",[$data['email'],$id]);
}
}
Session::flash('sm',$request['name'] . '`s Has Been Updated');
}
Web:
Route::get('user/account', 'UserController#account');
Route::post('user/account', 'UserController#postAccount');
HTML:
#extends('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h1>Edit Your Account -</h1>
</div>
<div class="row" style="margin-left:30%;">
<div class="col-md-6">
<form action="" method="post">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{ $user['id'] }}">
<div class="form-group">
<label for="name"></label>
<input value="{{ $user['name'] }}" type="text" name="name"
class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="email"></label>
<input value="{{ $user['email'] }}" type="text" name="email"
class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="editpassword"></label>
<input type="password" name="password" class="form-control"
id="editpassword" placeholder="Edit Password">
</div>
<div class="form-group">
<label for="editpasswordconf"></label>
<input type="password" name="password_confirmation" class="form-
control" id="editpasswordconf" placeholder="Confirm New Password">
</div>
<div class="form-group text-center">
<input type="submit" name="submit" value="Update Details" class="btn
btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Your AccountController should look like this:
public function edit($request, Account $account){
return view('forms.account', [
'account' => $account,
'title' => 'Edit Account'
]);
}
public function update(AccountRequest $request, Account $account){
$account->update($request->all());
Session::flash('sm', $account->name . ' Has Been Updated');
return redirect()->back();
}
AccountRequest:
public function rules()
{
return [
'name' => 'required|min:2|max:70',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:10|confirmed',
];
}
That is about as much code as you need for this process... please read the documentation for Eloquent https://laravel.com/docs/5.4/eloquent

How to insert multiple rows in laravel 5?

I want to insert an array with an id :
create.blade :
{{ Form::open(array('route' => 'Charge.store','method'=>'POST')) }}
<select id="disabledSelect" class="form-control" name="Facture_id">
<option value="{{ $Facture->id }}" >{{ $Facture->Num }}</option>
</select>
<br/>
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Title]" placeholder="libelé"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Quantity]" placeholder="Quantité"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Price]" placeholder="Prix unitaire "/>
</div>
<div class="form-group">
<input type="button" class="btn btn-default" value="Ajouter" onclick="createNew()" />
</div>
<div id="mydiv"></div>
</div>
<br/>
<div class="form-group">
<input type="submit" value="Ajouter" class="btn btn-info">
Cancel
</div>
{{ Form::close() }}
<script>
var i = 2;
function createNew() {
$("#mydiv").append('<div class="form-group">'+'<input type="text" name="rows[' + i +'][Title]" class="form-control" placeholder="libelé"/>'+
'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Quantity]" class="form-control" placeholder="Quantité"/>'+'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Price]" class="form-control" placeholder="Prix unitaire "/>'+'</div>'+'<div class="form-group">'+
'<input type="button" name="" class="btn btn-default" value="Ajouter" onclick="createNew()" />'+
'</div><br/>');
i++;
}
</script>
here is my controller , when I tried to submit the form , it inject rows with value of 0.
What should I do ? I tried to use elequent bolk data , but the problem remain the same:
public function store(Request $request)
{
// validated input request
$this->validate($request, [
'Facture_id' => 'required',
]);
// create new task
$rows = $request->input('rows');
foreach ($rows as $row)
{
$Charges[] = new Charge(array(
'course_id'=>$request->input('Facture_id'),
'Title'=>$row['Title'],
'Quantity'=>$row['Quantity'],
'Price'=>$row['Price'],
));
}
Charge::create($Charges);
return redirect()->route('Charge.index')->with('success', 'Your task added successfully!');
}
You can use insert() method:
foreach ($rows as $row)
{
$charges[] = [
'course_id' => $request->input('Facture_id'),
'Title' => $row['Title'],
'Quantity' => $row['Quantity'],
'Price' => $row['Price'],
];
}
Charge::insert($charges);
Don't forget to add all column names you use to a $fillable array:
$fillable = ['course_id', 'Title', 'Quantity', 'Price'];

Resources