I have a form that allows the user to upload 3 files.
Here is the Controller function called :
public function registerUpdate(CardAvsRequest $request){
$id = Auth::user()->id;
$first_name = User::find($id)->student->first_name;
$last_name = User::find($id)->student->last_name;
$name = $first_name . " " . $last_name;
$message = "";
if ($request->hasFile('carte-id'))
{
$image1 = $request->file('carte-id');
if($image1->isValid())
{
if ($request->hasFile('avs'))
{
$image2 = $request->file('avs');
if($image2->isValid())
{
if ($request->hasFile('permit'))
{
$image3 = $request->file('permit');
if($image3->isValid())
{
$path = config('card.path')."/$id";
$name = "carte-id.".$image1->getClientOriginalExtension();
$image1->move($path, $name);
$path = config('card.path')."/$id";
$name = "avs.".$image2->getClientOriginalExtension();
$image2->move($path, $name);
$path = config('card.path')."/$id";
$name = "permit.".$image3->getClientOriginalExtension();
$image3->move($path, $name);
$message = "Super ! Vous avez importé tous les fichiers nécessaires.";
//ici on dit dans la DB que l'utilisateur à uploadé tous les fichiers
}
}
}
}
}
}
return redirect()->route('account', $id)->with('message', $message);
}
So the Validation rules are set in CardAvsRequest.php :
class CardAvsRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'carte-id' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
'avs' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
'permit' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
];
}
}
I would like to know how to display errors if a file isn't validated.
Isn't it supposed to work like this ?
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Any ideas ?
This is how Laravel 5.2 documentation suggestion to validate input and return error if any. The view looking good and will display error if occurred.
public function store(Request $request)
{
$rule = 'required|file|mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000';
$validator = Validator::make($request->all(), [
'file_one' => $rule,
'file_two' => $rule,
'file_three' => $rule,
]);
if ($validator->fails()) {
return redirect('account')
->withErrors($validator)
->withInput();
}
// no errors proceed managing your files
}
Yes but in that case you have to remember that you have to put that code:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
In form file.
Related
I´m trying to send an email confirmation when a contact form is submitted. So, I have a controller to do it and all it works fine.
The only problem is due to a textarea field which is making problems to me.
This is the output problem:
[previous exception] [object] (TypeError(code: 0): htmlspecialchars(): Argument #1 ($string) must be of type string, Illuminate\\Mail\\Message given at D:\\Proyectos\\PÁGINA PERSONAL\\profesional_website\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\helpers.php:118)
So, I'm debugging to check variable type and I checked that it was a string. I tried to parse such as strval($message) and concatenating such as trim($message." ") but it didn't work.
I attach controller code:
class EmailController extends Controller
{
function sendEmail (Request $request) {
Log::debug(gettype($request->description));
$formData = array(
'name' => $request->name,
'last_names' => $request->last_names,
'mail'=> $request->email,
'message'=> $request->description,
'phone' => $request->phone
);
Mail::to($formData['mail'])->send(new NotifyMail($formData));
if (Mail::failures()) {
$response['success'] = false;
$response['message'] = 'Ha ocurrido un error';
return $response;
}else{
$response['success'] = true;
$response['message'] = 'Mensaje enviado correctamente';
return $response;
}
}
}
And the blade view:
<div style="background-color:#ffcc66;text-align:center;padding:30px 0">
<h1 style="color: #fff;">¡Bienvenido a alexdevs, {{$name}}!</h1>
<p style="color: #fff;">Si este es tu problema:</p>
<p style="color: #fff;padding:20px 50px">{{$message}}</p>
<p style="color: #fff">¡Encontraremos una solución perfecta!</p>
<p style="color: #fff">Me pondré en contacto contigo lo antes posible a través de tu correo: {{$mail}}</p>
<h3 style="color: #fff;">¡Muchas gracias!</h3>
<img src="{{asset('img/negative_rounded_brand.png')}}" alt="alexdevs_logo"
style="height:50px;width:50px;margin-top:30px">
</div>
And this is the Mailable class:
class NotifyMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('mail.client', $this->data);
}
}
i have flashMessage trait which controllers flashing messages
Trait FlashMessages
{
protected $errorMessages = [];
protected $infoMessages = [];
protected $successMessages = [];
protected $warningMessages = [];
/**
* #param $message
* #param $type
*/
protected function setFlashMessage($message, $type)
{
$model = 'infoMessages';
switch ($type) {
case 'info' : {
$model = 'infoMessage';
}
break;
case 'error' : {
$model = 'errorMessages';
}
break;
case 'success' : {
$model = 'successMessages';
}
break;
case 'warning' : {
$model = 'warningMessages';
}
break;
}
if (is_array($message)) {
foreach ($message as $key => $value) {
array_push($this->$model, $value);
}
} else array_push($this->$model, $message);
}
public function getFlashMessages(): array
{
return [
'error' => $this->errorMessages,
'info' => $this->infoMessages,
'success' => $this->successMessages,
'warning' => $this->warningMessages,
];
}
public function showFlashMessages()
{
session()->flash('error', $this->errorMessages);
session()->flash('info', $this->infoMessages);
session()->flash('success', $this->successMessages);
session()->flash('warning', $this->warningMessages);
}
}
so i include it in my BaseController.php which its source is as follows.
class BaseController extends Controller
{
use FlashMessages;
protected $data = null;
protected function setPageTitle($title, $subTitle)
{
view()->share(['pageTitle' => $title, 'subTitle' => $subTitle]);
}
protected function showErrorPage($errorCode = 404, $message = null)
{
$data['message'] = $message;
return response()->view('errors.'.$errorCode, $data, $errorCode);
}
protected function responseJson($error = true, $responseCode = 200, $message = [], $data = null): \Illuminate\Http\JsonResponse
{
return response()->json([
'error' => $error,
'response_code' => $responseCode,
'message' => $message,
'data' => $data
]);
}
protected function responseRedirect($route, $message, $type = 'info', $error = false, $withOldInputWhenError = false): \Illuminate\Http\RedirectResponse
{
$this->setFlashMessage($message, $type);
$this->showFlashMessages();
if ($error && $withOldInputWhenError) {
return redirect()->back()->withInput();
}
return redirect()->route($route);
}
protected function responseRedirectBack($message, $type = 'info'): \Illuminate\Http\RedirectResponse
{
$this->setFlashMessage($message, $type);
$this->showFlashMessages();
return redirect()->back();
}
}
and my GalleryController extends Basecontroller and store method is as follows for storing new gallery
public function store(Request $request): \Illuminate\Http\RedirectResponse
{
// dd($request->all());
$request->validate([
'name' => 'required',
'address' => 'required',
'city_id' => 'required|integer',
]);
//create new gallery instance
// dd($request);
$gallery = new Gallery();
$gallery->name = $request->name;
$gallery->address = $request->address;
$gallery->city_id = $request->city_id;
$gallery->user_id = Auth::user()->id;
// dd($gallery);
// dump($request->toArray());
$gallery->save();
if (!$gallery) {
return $this->responseRedirectBack('Error occured while creating Gallery');
}
return $this->responseRedirect('galleries.index', 'New Gallery added');
}
lastly i included in my index.blade.php file with flash.blade.php partial which its source code is
#php
$errors = Session::get('error');
$messages = Session::get('success');
$info = Session::get('info');
$warnings = Session::get('warning');
#endphp
#if ($errors) #foreach($errors as $key => $value)
<div class="alert alert-danger alert-dismissible" role="alert">
<button class="close" type="button" data-dismiss="alert">×</button>
<strong>Error!</strong> {{ $value }}
</div>
#endforeach #endif
#if ($messages) #foreach($messages as $key => $value)
<div class="alert alert-success alert-dismissible" role="alert">
<button class="close" type="button" data-dismiss="alert">×</button>
<strong>Success!</strong> {{ $value }}
</div>
#endforeach #endif
#if ($info) #foreach($info as $key => $value)
<div class="alert alert-info alert-dismissible" role="alert">
<button class="close" type="button" data-dismiss="alert">×</button>
<strong>Info!</strong> {{ $value }}
</div>
#endforeach #endif
#if ($warnings) #foreach($warnings as $key => $value)
<div class="alert alert-warning alert-dismissible" role="alert">
<button class="close" type="button" data-dismiss="alert">×</button>
<strong>Warning!</strong> {{ $value }}
</div>
#endforeach #endif
but when i try to save new gallery it is returning an error in flashMessage.php trait file line 46 which is as follows.
if (is_array($message)) {
foreach ($message as $key => $value) {
array_push($this->$model, $value);
}
} else array_push($this->$model, $message);
the error code is comming from else block. so how can i fix this? this code worked with my city controller but not working with this GalleryController. i know ther error is array_push is expecting that the first argument should be an array. but but it says in else bock that $this->$model is null, why as it worked with my other controller, plz help
thanks.
I'm having trouble in deleting a record that has file in it. Below is the code.
delete file method :
private function deletePDF(Journal $journal) {
$exist = Storage::disk('file')->exists($journal->file);
if (isset($journal->file) && $exist) {
$delete = Storage::disk('file')->delete($journal->file);
if ($delete) {
return true;
}
return false;
}
}
Destroy method :
public function destroy(Journal $journal, EditionRequest $request) {
$this->deletePDF($journal);
$journal->delete();
return redirect()->route('edition', ['id' => $request->id]);
}
The result game me nothing, it's just return to the page where the record belongs and does not deleting the record. I used the same code for another project with the same laravel version and it's working, but for some reasons it doesn't work here and I'm a lil bit confused.
Update :
EditionRequest :
public function rules() {
// Cek apakah CREATE atau UPDATE
$id = $this->get('id');
if ($this->method() == 'PATCH') {
$volume_rules = 'required|integer|unique_with:edition,number,' . $id;
$number_rules = 'required|integer';
} else {
$volume_rules = 'required|integer|unique_with:edition,number';
$number_rules = 'required|integer';
}
return [
'volume' => $volume_rules,
'number' => $number_rules,
'cover' => 'sometimes|image|max:15000|mimes:jpeg,jpg,bmp,png',
];
}
If it returns to the same page as before, you probably have a validation error in your request!
You can check the errors easily by adding the following snippet to your view:
#if(count($errors) > 0)
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
With this you should be able to see what's going wrong. Let me know if it worked :)
edit
public function rules() {
// Cek apakah CREATE atau UPDATE
$id = $this->get('id');
if ($this->method() == 'PATCH') {
$volume_rules = 'required|integer|unique_with:edition,number,' . $id;
$number_rules = 'required|integer';
}
else if($this->method() == 'DELETE'){
//your delete validation rules rules
$volume_rules = ''
$number_rules= '';
}
else {
$volume_rules = 'required|integer|unique_with:edition,number';
$number_rules = 'required|integer';
}
return [
'volume' => $volume_rules,
'number' => $number_rules,
'cover' => 'sometimes|image|max:15000|mimes:jpeg,jpg,bmp,png',
];
}
You might even want to not use the request youre using now, which would give you this:
public function destroy(Journal $journal, Request $request)
i'm trying to use callback to simply to check my form input, the offical code is here: https://laravel.com/docs/5.2/validation
the following is my function
public function addthread(Request $request) {
$input = $request->all();
$rules = array('title' => 'required|unique:thread|max:255');
$message = array('title.required' => 'The :attribute field is aaa required.');
$validator = Validator::make($input, $rules, $message);
$validator->after(function($validator) {
if ($this->checkOpt()) {
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
});
if ($validator->fails()) {
return redirect('addthreadhtml')->withErrors($validator)->withInput();
}
}
public function checkOpt() {
return false;
}
the blade tpl:
#if (count($errors) > 0)
<div class="container" stytle="max-width:80%">
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
The num_opt error never print out, any idea?
checkOpt() is returning FALSE, so the code will never enter the if statment.
if ($this->checkOpt()) { // this is returning false, right ?? so, its not adding the error
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
Your checkOpt() always returns false, so your condition won't ever be satisfied.
I am trying to make a authentication system and the only issue that I am having is that it will not display the errors if the wrong creds are used. It shows the error when one of the fields is empty but not when they are both filled with wrong info. Can someone help me figure out what is wrong? Thanks for all the help!
Here is my view
{{ Form::open([
"route"=>"user/login",
"autocomplete"=>"off"
]) }}
{{ Form::label("username", "Username") }}
{{ Form::text("username", Input::old("username"), [
"placeholder"=>"Username"
]) }}
{{ Form::label("password", "Password") }}
{{ Form::password("password", [
"placeholder"=>"Password"
]) }}
#if($error = $errors->first("password"))
<div class="error">
{{ $error }}
</div>
#endif
{{ Form::submit("Login") }}
{{ Form::close() }}
here is the controller
<?php
use Illuminate\Support\MessageBag;
class UserController extends BaseController
{
public function loginAction()
{
$errors = new MessageBag();
if($old = Input::old("errors")) {
$errors = $old;
}
$data = [
"errors"=>$errors
];
if(Input::server("REQUEST_METHOD") == "POST") {
$validator = Validator::make(Input::all(), [
"username"=>"required",
"password"=>"required"
]);
if($validator->passes()) {
$credentials = [
"username"=>Input::get("username"),
"password"=>Input::get("password")
];
if(Auth::attempt($credentials)) {
//return Redirect::route("user/login");
echo "login success";
}
} else {
echo "Login failed";
$data["errors"] = new MessageBag([
"password"=>[
"Username and/or password invalid."
]
]);
$data["username"] = Input::get("username");
return Redirect::route("user/login")
->withInput($data);
}
}
return View::make("user/login", $data);
}
}
It looks like you are not displaying any message if the authentication fails. Auth::attempt() will try to match the username and password and if it fails it should add something to the errors array.
if(Auth::attempt($credentials)) {
//return Redirect::route("user/login");
echo "login success";
}
else // add this
{
echo 'login failed - username and/or password provided are not correct';
}
That said, you probably need to add an else statement here.