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.
}
Related
I am trying to insert data in Laravel using DB
code:
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ExamController;
Route::get('/', [ExamController::class, 'Index']);
Route::post('/exam-sub', [ExamController::class, 'Insertexam'])->name('sub')
welcome.blade.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{ URL::asset('css/test.css') }}" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<title>Quiz app</title>
</head>
<body bgcolor="green">
<form action="{{ route('sub') }}" method="post">
#csrf
<div class="container mb-3">
#if(Session::has('exam_submitted'))
<div class="alert alert-success">
{{ Session::get('exam_submitted') }}
</div>
#endif
<div class="form-outline">
<label class="form-label" for="form3Example1">First name</label>
<input type="text" id="form3Example1" class="form-control" name="first_name"/>
#error('first_name')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<div class="form-outline">
<label class="form-label" for="form3Example1">SEC NAME</label>
<input type="text" id="form3Example1" class="form-control" name="sec_name"/>
#error('sec_name')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<div class="form-outline">
<label class="form-label" for="form3Example1">EMAIL</label>
<input type="text" id="form3Example1" class="form-control" name="email"/>
#error('email')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<div class="form-outline">
<label class="form-label" for="form3Example1">PASSWORD</label>
<input type="password" id="form3Example1" class="form-control" name="password"/>
#error('password')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<h1 class="color-grey">test</h1>
<hr style="width: 30%; font-weight: 700; height:3px; background-color:black;">
<div class="form-outline">
<label class="form-label" for="form3Example1">24x90</label>
<input type="text" id="form3Example1" class="form-control" name="question1"/>
#error('question-1')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<div class="form-outline">
<label class="form-label" for="form3Example1">45x80</label>
<input type="text" id="form3Example1" class="form-control" name="question2" />
#error('question-2')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<div class="form-outline">
<label class="form-label" for="form3Example1">100x10</label>
<input type="text" id="form3Example1" class="form-control" name="question3"/>
#error('question-3')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<div class="form-outline">
<label class="form-label" for="form3Example1">10x10</label>
<input type="text" id="form3Example1" class="form-control" name="question4"/>
#error('question-4')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
<br>
<button class="btn btn-outline-primary btn-block btn-lg">Submit test</button>
</div>
</form>
<div class="btn"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
</body>
</html>
ExamController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ExamController extends Controller
{
public function Index() {
return view('welcome');
}
public function Insertexam(Request $request) {
$validatedata = $request->validate([
'id' => mt_rand(1, 1000),
'first_name' => 'required',
'sec_name' => 'required',
'email'=> 'required|email',
'password' => 'required|min:8|max:24',
'question-1' => 'required|int',
'question-2' => 'required|int',
'question-3' => 'required|int',
'question-4' => 'required|int',
]);
DB::table('exam')->insert([
'Firstname' => $request->first_name,
'Secondname' => $request->body,
'email' => $request->email,
'password' => $request->password,
'question1' => $request->question1,
'question2' => $request->question2,
'question3' => $request->question3,
'question4' => $request->question4,
]);
return back()->with('exam_submitted','Exam submitted successfully contact you mr for the results good luck');
}
}
The problem is when inserting data it shows this:
array_map(): Argument #2 ($array) must be of type array, int given
The problem is with this 'id' => mt_rand(1, 1000), try to remove it.
$validatedata = $request->validate([
'id' => mt_rand(1, 1000),
'first_name'=> 'required',
'sec_name'=>'required',
'email'=> 'required|email',
'password' => 'required|min:8|max:24',
'question-1' => 'required|int',
'question-2' => 'required|int',
'question-3' => 'required|int',
'question-4' => 'required|int',
]);
Here is the code for controller:
public function save_product(Request $request){
$request->validate([
'product_name' => 'required',
'product_price' => 'required',
'product_category' => 'required',
'description' => 'nullable',
'image1' => 'required',
'image2' => 'nullable',
'image3' => 'nullable',
], [
'product_name.required' => 'Product name field required',
'product_price.required' => 'Asking price field required',
'product_category.required' => 'Product category field required',
'image1.required' => 'You need a upload image-1 field',
]);
if($request->hasFile('image1') || $request->hasFile('image2') || $request->hasFile('image3')){
$file1 = $request->file('image1');
$file2 = $request->file('image2');
$file3 = $request->file('image3');
$text1 = $file1->getClientOriginalExtension();
$text2 = $file2->getClientOriginalExtension();
$text3 = $file3->getClientOriginalExtension();
$fileName1 = time().'.'.$text1;
$fileName2 = time().'.'.$text2;
$fileName3 = time().'.'.$text3;
$file1->move('uploads/product_image', $fileName1);
$file2->move('uploads/product_image', $fileName2);
$file3->move('uploads/product_image', $fileName3);
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
}
return redirect()->route('add_product')
->with('success','Successfully added Product!');
}
Here is the code for blade template:
#extends('admin.layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
#include('pages.partials.flash_message')
</div>
</div>
</div>
<div class="card card-default">
<div class="card-header card-header-border-bottom">
<h2>Add Product</h2>
</div>
<div class="card-body">
<form action="{{route('save_product')}}" method="POST">
#csrf
<div class="form-group">
<label for="exampleFormControlSelect12">Select Category</label>
<input type="text" class="form-control" placeholder="Enter Arrival Time"
id="exampleFormControlSelect12" name="product_category" list="product_category"
autocomplete="off">
<datalist class="form-control" id="product_category" style="display: none" >
<option value="Women Clothes"></option>
<option value="Jewellery"></option>
<option value="Shoes"></option>
<option value="Sun Glass"></option>
<option value="Hair Band"></option>
</datalist>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-1</label>
</div>
#if ($errors->has('image1'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image1') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image1" class="custom-file-input" id="inputGroupFile01"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-2</label>
<small>*Optional</small>
</div>
#if ($errors->has('image2'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image2') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image2" class="custom-file-input" id="inputGroupFile02"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="inputGroupFile02">Upload Product Image-3</label>
<small>*Optional</small>
</div>
#if ($errors->has('image3'))
<span class="text-danger" style="font-weight: bold">{{ $errors->first('image3') }}
</span>
#endif
<div class="input-group my-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload Image</span>
</div>
<div class="custom-file">
<input type="file" name="image3" class="custom-file-input" id="inputGroupFile03"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Product Name or Title</label>
<input type="text" name="product_name" class="form-control"
id="exampleFormControlInput1" placeholder="Enter Product Name or Title">
#if ($errors->has('product_name'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_name') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Asking Price</label>
<input type="number" name="product_price" class="form-control"
id="exampleFormControlInput2" placeholder="Enter Asking Price">
#if ($errors->has('product_price'))
<span class="text-danger" style="font-weight: bold">{{ $errors-
>first('product_price') }}</span>
#endif
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Product Description</label>
<textarea class="form-control" name="product_description"
id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<div class="form-footer pt-4 pt-5 mt-4 border-top">
<button type="submit" class="btn btn-primary btn-default">Submit</button>
</div>
</form>
</div>
</div>
#endsection
Route:
Route::post('/admin/add_product','App\Http\Controllers\Admin\AdminController#save_product')
->name('save_product')->middleware('admin');
Model:
protected $fillable = [
'product_name',
'product_category',
'product_price',
'description',
'image1',
'image2',
'image3',
];
Migration:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->string('product_category');
$table->string('product_price');
$table->text('description')->nullable();
$table->string('image1');
$table->string('image2')->nullable();
$table->string('image3')->nullable();
$table->timestamps();
});
}
I can't find any error in my code please help me to find out. Thanks in advance.
You have to make separate if conditions for each image. Try this:
$fileName1='';
$fileName2='';
$fileName3='';
if($request->hasFile('image1')) {
$file1 = $request->file('image1');
$text1 = $file1->getClientOriginalExtension();
$fileName1 = time() . '.' . $text1;
$file1->move('uploads/product_image', $fileName1);
}
if($request->hasFile('image2')) {
$file2 = $request->file('image2');
$text2 = $file2->getClientOriginalExtension();
$fileName2 = time() . '.' . $text2;
$file2->move('uploads/product_image', $fileName2);
}
if($request->hasFile('image3')) {
$file3 = $request->file('image3');
$text3 = $file3->getClientOriginalExtension();
$fileName3 = time() . '.' . $text3;
$file3->move('uploads/product_image', $fileName3);
}
$product = Product::create([
'image1'=>$fileName1,
'image2'=>$fileName2,
'image3'=>$fileName3,
'product_category' => trim($request->input('product_category')),
'product_name' => trim($request->input('product_name')),
'product_price' => trim($request->input('product_price')),
'description' => trim($request->input('description')),
]);
if($product){
return redirect()->route('add_product')->with('success','Successfully added Product!');
}
else{
return redirect()->back()->with('error','Error!');
}
using enctype="multipart/form-data" inside form tag .
I want to implement locally forgot password functionality by answering a few security questions where user can reset his/her password without sending reset links via emails.
Here I have tried the below code, in updatePassword.blade.php the email, password, and password-confirm validation is not working so I implement it in the UserControler when I put the email address which is not in the database, or when I put the miss-matched password in the password and password-confirm inputs it throws the below error, but if I put the correct email and password with the matched password in the password and password-confirm inputs it resets my password, I don't know what is wrong.
Any kind of help will be highly appreciated.
ErrorException (E_ERROR) Trying to get property of non-object (View:
C:\xampp\htdocs\Bookstore\resources\views\layouts\layout.blade.php)
(View:
C:\xampp\htdocs\Bookstore\resources\views\layouts\layout.blade.php)
Here are routes in web.php
Route::get('getview', [
'uses' => 'HomeController#getview',
'as' => 'check.getview'
]);
Route::post('chekQuestions', [
'uses' => 'HomeController#chekQuestions',
'as' => 'check.question'
]);
Route::post('updagePassword', [
'uses' => 'HomeController#updagePassword',
'as' => 'update.question'
]);
Here is the code in Controller
public function getview()
{
return view('auth.test');
}
public function chekQuestions(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'answerQuestionOne' => 'required',
'answerQuestionTwo' => 'required'
]);
$user = User::first();
if ($user->email != $request->email) {
return redirect()
->back()
->with(Session::flash('message', 'دا ایمل شتون نلری'))
->withInput();
}
if ($user->answerQuestionOne != $request->answerQuestionOne) {
return redirect()
->back()
->with(Session::flash('message2', 'ځواب مو مطابقت نلری'))
->withInput();
}
if ($user->answerQuestionTwo != $request->answerQuestionTwo) {
return redirect()
->back()
->with(Session::flash('message3', 'ځواب مو مطابقت نلری'))
->withInput();
}
return view('auth.updatePassword',compact('user'));
}
public function updagePassword(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|confirmed|min:8'
]);
$user = User::first();
if ($user->email != $request->email) {
return redirect()
->back()
->with(Session::flash('message', 'دا ایمل شتون نلری'))
->withInput();
} elseif ($request->password_confirmation != $request->password) {
return redirect()
->back()
->with(Session::flash('message2', 'دا ایمل شتون نلری'))
->withInput();
} else {
$user->where('email', $request->email)->update([
'password' => Hash::make($request->password)
]);
return redirect()->route('login');
}
}
Here is the link going to the test view
<a style="font-size: 15px;" href="{{route('check.getview')}}" class="to_register">د پټ نو بیا راګرځول د امنتی پوښتنو له لاری </a>
Here test view
<div class="x_content">
<br>
<form method="POST" action="{{route('check.question')}}" class="form-horizontal form-label-left">
#csrf
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">ایمل
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#if(Session::has('message'))
<p class="bg-danger">{{session('message')}} </p>
#endif
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">
لومړۍ امنیتي پوښتنه <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="answerQuestionOne" placeholder="لومړۍ امنیتي پوښتنه" type="text" class="form-control #error('answerQuestionOne') is-invalid #enderror" name="answerQuestionOne" value="{{ old('answerQuestionOne') }}" required autocomplete="answerQuestionOne" autofocus>
#if(Session::has('message2'))
<p class="bg-danger">{{session('message2')}} </p>
#endif
#error('answerQuestionOne')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror </div>
</div>
<div class="form-group">
<label for="middle-name" class="control-label col-md-3 col-sm-3 col-xs-12">
دوهمه امنیتي پوښتنه </label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="answerQuestionTwo" placeholder="دوهمه امنیتي پوښتنه " type="text" class="form-control #error('answerQuestionTwo') is-invalid #enderror" name="answerQuestionTwo" value="{{ old('answerQuestionTwo') }}" required autocomplete="answerQuestionTwo" autofocus>
#if(Session::has('message3'))
<p class="bg-danger">{{session('message3')}} </p>
#endif
#error('answerQuestionTwo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror </div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
{{-- <button type="submit" class="btn btn-primary">انصراف</button> --}}
<button type="submit" class="btn btn-success">خوندی کړی</button>
</div>
</div>
</form>
</div>
Here is the updatePassword.blade.php
<div class="x_content">
<br>
<form method="POST" action="{{route('update.question')}}" class="form-horizontal form-label-left">
#csrf
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">ایمل
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{{-- #foreach ($user as $getemail) --}}
{{-- value="{{ old('email') }}" --}}
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ $user->email }}" required autocomplete="email" autofocus>
{{-- #endforeach --}}
#if(Session::has('message'))
<p class="bg-danger">{{session('message')}} </p>
#endif
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">پټ نوم
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#if(Session::has('message2'))
<p class="bg-danger">{{session('message2')}} </p>
#endif
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">پټ تأیید
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{{-- <input id="passwordconfirm" type="password" class="form-control" name="passwordconfirm" required autocomplete="new-password">
--}}
<input id="password-confirm" type="password" placeholder="دپټنوم تأیید " class="form-control" name="password_confirmation" required autocomplete="new-password">
#if(Session::has('message3'))
<p class="bg-danger">{{session('message3')}} </p>
#endif
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
{{-- <button type="submit" class="btn btn-primary">انصراف</button> --}}
<button type="submit" class="btn btn-success">خوندی کړی</button>
</div>
</div>
</form>
</div>
try this
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|min:6',
'password_confirmation' => 'required|same:password'
]);
I found the solution by manually setting the validation messages
Code in the controller
public function getview(Request $request)
{
$user=new User();
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
return view('auth.question',compact('user','anserone','anstwo'));
}
public function chekQuestions(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'answerQuestionOne' => 'required',
'answerQuestionTwo' => 'required'
]);
$user = User::where('email', $request->email)->first();
if ( $user == null) {
//
$user=new User();
$user->email= $request->email;
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
Session::flash('message', 'دا ایمل شتون نلری');
return view('auth.question',compact('user','anserone','anstwo'));
}
if ( $user->answerQuestionOne == null || $user->answerQuestionTwo == null) {
//
$user=new User();
$user->email= $request->email;
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
Session::flash('message4', 'هیڅ مورد نشته، لمړی تاسی خپل امنیتی ځوابونه خوندی کړی');
return view('auth.question',compact('user','anserone','anstwo'));
}
if ($user->answerQuestionOne != $request->answerQuestionOne) {
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
Session::flash('message2', 'دپښتنو ځوابونه مو ناسم وو');
return view('auth.question',compact('user','anserone','anstwo'));
}
if ( $user->answerQuestionTwo != $request->answerQuestionTwo) {
$anstwo = $request->answerQuestionTwo;
$anserone= $request->answerQuestionOne;
Session::flash('message3', 'دپښتنو ځوابونه مو ناسم وو');
return view('auth.question',compact('user','anstwo','anserone'));
}
return view('auth.updatePassword',compact('user'));
}
public function updagePassword(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|min:8'
]);
// $user = User::first();
$user = User::where('email', $request->email)->first();
if ( $user == null) {
//
$user=new User();
$user->email= $request->email;
// $anserone= $request->answerQuestionOne;
// $anstwo = $request->answerQuestionTwo;
Session::flash('message', 'دا ایمل شتون نلری');
return view('auth.updatePassword',compact('user'));
}
if ($request->password_confirmation != $request->password) {
Session::flash('message3', 'پټ نوم مطابقت نلری');
return view('auth.updatePassword',compact('user'));
}
$user->where('email', $request->email)->update([
'password' => Hash::make($request->password)
]);
return redirect()->route('login');
}
I want to edit form update only address, email and password. How to change password? The old password is important.
edit.blade.php
<form method="POST" action="{{ route('update') }}">
#csrf
{{ method_field('PATCH') }}
<div class="form-group row">
<label for="email" class="col-md-1 col-form-label text-md-right">{{ __('Email') }}</label>
<div class="col-md-5">
<input id="email" type="text" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') ? : user()->email }}" required autocomplete="email" autofocus>
#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-1 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-5">
<input id="password" type="text" class="form-control #error('password') is-invalid #enderror" name="password" value="{{ old('password') }}" required autocomplete="password" autofocus>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="address" class="col-md-1 col-form-label text-md-right">{{ __('Address') }}</label>
<div class="col-md-5">
<textarea id="address" type="text" class="form-control #error('address') is-invalid #enderror" name="address" required autocomplete="address" autofocus>{{ old('address') ? : user()->address }}</textarea>
#error('address')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-1">
<button type="submit" class="btn btn-block btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
Route
Route::post('update', 'Auth\RegisterController#sqlupdate')->name('update');
RegisterController
public function sqlupdate(Request $request)
{
Auth::user()->update([
'address' => $request['address'],
'email' => $request['email'],
]);
$hashedPassword = auth()->user()->password;
if (Hash::check($request->oldpassword, $hashedPassword)){
$user = User::findOrFail(Auth::id());
$user->password = Hash::make($request->password);
}
return redirect()->back();
}
Just read the below code carefully :-
/**
* Admin My profile : Password update.
*
* #param Request $request
* #param $id
* #return \Illuminate\Http\Response
*/
public function updatePassword(Request $request,$id = 0)
{
$validate = Validator::make($request->all(),[
'old_password' => 'required',
'password' => 'required|confirmed|min:8',
'password_confirmation' => 'required|min:8',
]);
$getUserData = Admin::where('id',$id)->first();
if($getUserData === null) {
return redirect()->back()->with([
'status' => 'warning',
'title' => 'Warning!!',
'message' => 'Invalid Admin ID.'
]);
}
$validate->after(function ($validate) use ($request,$getUserData,$id) {
if(!Hash::check($request->get('old_password'),$getUserData->password)){
$validate->errors()->add('old_password', 'Wrong old password');
}
});
if($validate->fails()){
return redirect()->back()->withErrors($validate)->withInput();
}
try{
$getUserData->update([
'password' => Hash::make($request->get('password'))
]);
return redirect()->back()->with([
'status' => 'success',
'title' => 'Success!!',
'message' => 'Admin password updated successfully.'
]);
}catch (Exception $e){
return redirect()->back()->with([
'status' => 'error',
'title' => 'Error!!',
'message' => $e->getMessage()
]);
}
}
With the above method you'll get the idea of how we update password, this is from one of my project i've created three field for that here is the screenshot of view :-
I hope this will help
Further more update here is the small snippet for update method
specially
$getOldPassword = User::where('id',$id)->first();
if($request->get('password') === null){
$password = $getOldPassword->password;
}else{
$password = Hash::make($request->get('password'));
}
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.