Frontend form Laravel Nova - laravel

I really like Laravel Nova but it's really complicated for a newbie like me to do something on the frontend that interacts with backend resources.
Can anyone tell me how to make a form insert data into a table from the frontend? Do I need to create a new external model? Can't interact with Nova resources?
Thanks in advance for enlightening me.
My form:
<form wire:submit.prevent="submit">
<div class="form-group">
<input type="text" class="form-control" id="code" placeholder="Introduzca código " name="code">
#error('code') <span class="text-danger">{{ $message }}</span> #enderror
</div><br>
<div class="form-group">
<input type="text" class="form-control" id="ip" placeholder="Introduzca IP " name="ip">
#error('ip') <span class="text-danger">{{ $message }}</span> #enderror
</div><br>
<div class="form-group">
<input type="text" class="form-control" id="access" placeholder="Introduzca access " name="access">
#error('access') <span class="text-danger">{{ $message }}</span> #enderror
</div><br>
<button type="submit" class="btn btn-block btn-primary">Crear Asistencia</button>
</form>
My function submit:
public function submit()
{
$this->validate([
'code' => 'required|min:4',
'ip' => 'required|min:15',
'access' => 'required|min:1',
]);
Attendance::create([
'code' => $this->code,
'ip' => $this->ip,
'access' => $this->access,
]);
session()->flash('message','asistencia creada correctamente');
return redirect(RouteServiceProvider::HOME);
}

Related

Check if at least one input has value with laravel controller

I have a simple form where the user should be able to only fill the inputs he wants but if the form hasn't at least one input filled, it should return a error message saying that the form can't be empty if he clicks the submit button.
Here's my form:
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<strong>{{ $message }}</strong>
</div>
#endif
</center>
<form action="{{ route('send-update') }}" method="POST" enctype="multipart/form-data"> #csrf
<label>Nome do projeto:</label>
<div class="input-group mb-3"><br>
<input type="text" class="form-control" name="project_name" aria-label="Username" aria-describedby="basic-addon1">
</div>
#error('project_name')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Descrição:</label>
<div class="input-group mb-3"><br>
<textarea class="form-control" name="desc" aria-label="With textarea"></textarea>
</div>
#error('desc')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Tem alguma imagem que queira mudar/inserir?</label>
<div class="input-group mb-3">
<input type="file" name="img" accept="image/*" class="form-control" id="inputGroupFile01">
</div>
#error('img')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<div class="input-group mb-3">
<input type="text" class="form-control" name="img_desc" placeholder="Diga-nos onde pretende mudar/adicionar">
</div>
#error('img_desc')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Tem mais informações? Insira um arquivo .txt, docx ou pdf</label>
<div class="input-group mb-3">
<input type="file" name="ficheiro" accept=".xlsx,.xls,.doc, .docx,.ppt, .pptx,.txt,.pdf" class="form-control" id="inputGroupFile01">
</div>
#error('ficheiro')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<input type="hidden" name="id" value="{{ request('id') }}">
<center> <button type="submit" class="btn btn-secondary ">Fazer pedido de atualização</button></center><br>
</form>
And here's the controller:
public function sendUpdate(Request $request){
$id = $request['id'];
$order = Order::where('id', $id)->first();
$validator = Validator::make($request->all(), [
'project_name' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'desc' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'img' => ['nullable', 'image', 'mimes:jpeg,png,jpg,svg', 'max:1024'],
'img_desc' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'ficheiro' => ['nullable', 'csv,txt,xlx,xls,pdf', 'max:2048'],
]);
if (request()->hasFile('ficheiro')){
if (request()->file('ficheiro')->isValid())
{
$fileName = $request->file('ficheiro')->getClientOriginalName();
$path = $request->file('ficheiro')->storeAs('files', $fileName, 'public');
}}
if (request()->hasFile('img')){
if (request()->file('img')->isValid())
{
$imageName = $request->file('img')->getClientOriginalName();
$pathImg = $request->file('img')->storeAs('files', $imageName, 'public');
}}
Update::create([
'customer_name' => $order->customer_name,
'customer_email' => $order->email,
'project_name' => $order->project_name,
'project_new_name' => $request['project_name'],
'description' => $request['desc'],
'image' => $pathImg ?? '',
'image_desc' => $request['img_desc'],
'ficheiro' => $path ?? '',
]);
return back()->with('success','Obrigado! Entraremos em contacto consigo em breve!');
}
I have no idea how to check if all inputs are empty in the controller . I've already tried this below, but it doesn't work. It keeps sending the form anyway.
if(count($request->all()) < 0) {
return dd('request all input empty.');
}
You can do it this way.
if(empty(array_filter($request->all()))){
//All fields are empty.
}

Error: 405 - Method not allowed while trying to update in Laravel

Current, I am working on a project using Laravel-5.8. I have a code to update data:
Controller
public function store_external_respondent(StoreAppraisalRespondentExternalRequest $request)
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
DB::beginTransaction();
try {
$respondent = AppraisalRespondent::create([
'fullname' => $request->fullname,
'respondent_email' => $request->respondent_email,
'company_name' => $request->company_name,
'is_internal' => 1,
]);
DB::commit();
Session::flash('success', 'Appraisal Respondent created successfully');
return redirect()->route('appraisal.appraisal_respondents.index');
} catch (Exception $ex) {
DB::rollback();
Session::flash('error', 'Action failed! Please try again');
return back();
}
}
route/web.php:
Route::group(['prefix' => 'appraisal', 'as' => 'appraisal.', 'namespace' => 'Appraisal', 'middleware' => ['auth']], function () {
Route::post('appraisal/appraisal_respondents/update_external_respondent/{id?}', 'AppraisalRespondentsController#update_external_respondent')->name('appraisal_respondents.update_external_respondent');
});
When I did php artisan route:list, I got:
| | POST | appraisal/appraisal/appraisal_respondents/update_external_respondent/{id?} | appraisal.appraisal_respondents.update_external_respondent | App\Http\Controllers\Appraisal\AppraisalRespondentsController#update_external_respondent | web,auth
update view blade
<button type="button" class="btn btn-sm btn-info mr-1 edit-respondent-respondent" data-toggle="modal" data-target="#edit_respondent_external{{ $respondentexternal->id }}">Edit</button>
<div class="modal fade" id="edit_respondent_external{{ $respondentexternal->id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{route('appraisal.appraisal_respondents.update_external_respondent',['id'=>$respondentexternal->id])}}" method="post" id="edit_respondent-external-form">
{{ csrf_field() }}
<input type="hidden" name="appraisal_identity_id" value="{{$identities->id}}">
<input type="hidden" name="employee_id" value="{{$employees->id}}">
<input name="_method" type="hidden" value="PUT">
<div class="modal-header">
Update Respondent (External)
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"> FullName:<span style="color:red;">*</span></label>
<input type="text" name="fullname" placeholder="Enter external respondent fullname here" class="form-control" value="{{old('fullname',$respondentexternal->fullname)}}">
#error('fullname')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"> Company:<span style="color:red;">*</span></label>
<input type="text" name="company_name" placeholder="Enter external respondent company here" class="form-control" value="{{old('company_name',$respondentexternal->company_name)}}">
#error('company_name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"> Respondent Email:<span style="color:red;">*</span></label>
<input type="text" name="respondent_email" placeholder="Enter external respondent email here" class="form-control" value="{{old('respondent_email',$respondentexternal->respondent_email)}}">
#error('respondent_email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" id="edit_respondent_external_btn-submit" class="btn btn-success btn-ok">Save</button>
</div>
</form>
</div>
</div>
</div>
When I submitted, I got this error:
405
Method Not Allowed.
Sorry, the page you are looking for could not be found. Go Back
In the console I have:
POST http://localhost:8888/myapp/appraisal/appraisal/appraisal_respondents/update_external_respondent/2 405 (Method Not Allowed)
How do I resolve this?
Also Why is appraisal repeated twice in
POST http://localhost:8888/myapp/appraisal/appraisal/appraisal_respondents/update_external_respondent/2 405 (Method Not Allowed)
Thanks
// STEP 1
Route::post('appra....
// STEP 2
<input name="_method" type="hidden" value="PUT">
So what's wrong?
please use {{method_field('check_your_route_type')}} below {{ csrf_field() }}
e.g : Route::put('url' ... should use {{method_field('PUT')}}

Reset password manually via answering the security questions without sending email - Laravel/auth

I am currently developing a simple Bookstore application with a few numbers of users on which sending emails are not needed because it will be implemented in local system so is there any way to customize laravel-auth for password reset function by adding a few security questions fields where user can reset his/her password without sending reset links via email.
Any kind of help will be highly appreciated.
here I tried the below code but id did not work
Code in web.php
Route::post('/main/checklogin', 'UserController#chekQuestions');
Code in userContoller
public function chekQuestions(Request $request)
{
$request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::first();
if($user->email == $request->email && $user->answerQuestionOne == $request->answerQuestionOne && $user->answerQuestionTwo == $request->answerQuestionTwo )
{
// $userEmail = DB::table( 'password_resets' )->where( 'token', $user->token );
// return view('auth.password.reset',compact($userEmail));
return view('auth.password.reset');
}
return response()->json( [
'error' => true,
'message' => 'We cannot find a user with that Email Address'
], 404 );
}
Code in reset password.blade
<div id="register" class="animate form registration_form">
<section class="login_content">
<form method="POST" action="{{ url('/main/checklogin') }}" >
#csrf
<h3>د پټ نو بیا راګرځولو لپاره لاندی امنتی پوښتنو ته ځواب ورکړی </h3>
<div class="form-group has-feedback">
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="form-control-feedback">
<i class="fa fa-envelope-o text-muted"></i>
</div>
</div>
<div>
<input id="answerQuestionOne" placeholder="لومړۍ امنیتي پوښتنه" type="text" class="form-control #error('answerQuestionOne') is-invalid #enderror" name="answerQuestionOne" value="{{ old('answerQuestionOne') }}" required autocomplete="answerQuestionOne" autofocus>
#error('answerQuestionOne')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div>
<input id="answerQuestionTwo" placeholder="دوهمه امنیتي پوښتنه " type="text" class="form-control #error('answerQuestionTwo') is-invalid #enderror" name="answerQuestionTwo" value="{{ old('answerQuestionTwo') }}" required autocomplete="answerQuestionTwo" autofocus>
#error('answerQuestionTwo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button type="submit" class="btn btn-default btn-block">خوندی کړی </button>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">
تاسو دمخه غړی یاست ننوتل
</p>
<div class="clearfix"></div>
<br />
</form>
</section>
</div>
You don't need Laravel implementation for this. Just Find a user with the given email and check the answers. After that update the user record with the new password.
In order to fetch user you should do this:
$data = $request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::where(['email' => $data['email'])->first();
After this just check the answers.
You also need to take the new password from user.

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.

Laravel always sets the default value

I am trying to do registration with user profile picture upload.(I am forced to do it this way)
I created the migration like this:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('nom');
$table->string('prenom');
$table->string('type')->default('visiteur');
$table->boolean('confirme')->default(false);
$table->string('email')->unique();
$table->string('password');
$table->string('photo_url')->default('default_photo_profile.jpg');
$table->rememberToken();
$table->timestamps();
});
the create function :
$request = request();
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
and the form for the file field is like this:
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
everything is working fine except the photo_url field, it always sets the default value in the migration and not the value I set in the create function.
$fullname is initiated and already declared.
the entire form :
<form method="POST" action="{{ route('register') }}" aria-label="{{ __('Register') }}" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<label for="nom" class="col-md-4 col-form-label text-md-right">Nom</label>
<div class="col-md-6">
<input id="nom" type="text" class="form-control{{ $errors->has('nom') ? ' is-invalid' : '' }}" name="nom" value="{{ old('nom') }}" required autofocus>
#if ($errors->has('nom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('nom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="prenom" class="col-md-4 col-form-label text-md-right">Prénom</label>
<div class="col-md-6">
<input id="prenom" type="text" class="form-control{{ $errors->has('prenom') ? ' is-invalid' : '' }}" name="prenom" value="{{ old('prenom') }}" required autofocus>
#if ($errors->has('prenom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('prenom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Mot de pass</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Mot de pass confirmation</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
</div>
</div>
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Envoyer
</button>
</div>
</div>
</form>
What is the problem?
Assuming you have a value for $photo_url, make sure you have 'photo_url' in your $fillables.
When you have $fillables, it only inserts (via User::create) what has in that array, otherwise it doesn't submit for that variable.
Your $fillables should look like this:
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
Add 'photo' in $fillable array in User model:
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'photo_url',
];
so according to your code in your model you have to add the photo_url in $fillable array like below.
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
okay now there are 3 ways to do it with $fillable is first way and you are doing it right now.
2nd way:
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
else
{
$fullname = "default_photo_profile.jpg";
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
and in your migration change this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
3rd way:
$fullname = "default_photo_profile.jpg";
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
okay these are the ways to do it. i would prefer first and second way 3rd one is lengthy.
Note: for 2nd and 3rd case you have to change your migration from this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
Hope you get it.

Resources