i have this as my function in my controller
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
$config= ['table'=>'users', 'length'=>10, 'prefix'=>'ID'];
$user_id = IdGenerator::generate($config);
//save profile picture if added
if($data->hasfile('profile')){
$file = $data['profile'];
$extension = $file->getClientOriginalExtension();
$profile_pic = time().'.'.$extension;
$file->move(public_path('images/user/'),$profile_pic);
}
$user =User::create([
'id' => $user_id,
'fullname' => $data['fullname'],
'phonenumber' => $data['phonenumber'],
// 'profile_image' => $profile_pic,
'district_id' => $data['district_id'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
BusinessModel::create([
'user_id' =>$user_id,
'business_name' => $data['business_name'],
'category' => $data['category'],
// 'tax_clearance'=> $data['tax'],
// 'business_certificate'=> $data['cecrtificate'],
// 'ppda'=> $data['ppda'],
// 'other_docs'=> $data['otherdocs']
]);
return($user);
}
the commented lines contains input type of file so when i try using hasfile() am getting an error expected type object found an array.
how do i fix this and get the files from the form and inserting them into the database.
Try adding request inside a function parameter like this, hope this will help
protected function create(request $data)
You are getting multiple files from your form , first check the input tag it should be like this.
name="photos[]" multiple
if you want to store multiple files.
Then in the controller
$files = $request->file('photos');
foreach($files as $file){
//your store logic here
}
Related
This is contact form. I would like to recive email and save this data to my mysql. I use Laravel. Email function works good. but There is a problem. I would like to store all data at "function complete".
I validate all data at "function confirm" This is confirm screen page so user still not submit yet. I tried to write code like this at "function complete" but error say "Undefined variable: request" Could you teach me how to fix my code please?
public function confirm(Request $request)
{
$rules = [
'title' => 'required',
'search' => 'required',
'amount' => 'required|integer',
'email' => 'required|email',
'body' => 'required',
];
$this->validate($request, $rules);
$data = $request->all();
$request->session()->put($data);
return view('mail.confirm', compact("data"));
}
public function complete()
{
$data = $request->all(); # 3)
$request->session()->put($data); # 4)
Contact::create($request->all());
$data = session()->all();
Mail::send([ ・・・
You have to pass the parameter type $request as you did in confirm function.In your complete function, you don't declare $request variable and accessing it without declaration
public function confirm(Request $request)
{
$rules = [
'title' => 'required',
'search' => 'required',
'amount' => 'required|integer',
'email' => 'required|email',
'body' => 'required',
];
$this->validate($request, $rules);
$data = $request->all();
// setting session key value for you data
$request->session()->put('data',$data);
return view('mail.confirm', compact("data"));
}
/*
* complete page
*/
public function complete(Request $request)
{
// after confirm button click get data from session with key '#data' ;
$data = $request->session()->pull('data');
// get token value in variable and remove from data set so we can use mass assignement
$token = array_shift($data);
// creating record
$Contact = Contact::create($data);
Mail::send(['text' => 'mail.temp'], $data, function($message) use($data){
$message->to($data["email"])->bcc('lara_admin#sakura.ne.jp')->from('1110.ne.jp')->subject('thnak you。');});
Mail::send(['text' => 'mail.admintemp'], $data, function($message) use($data){
$message->to('lara_admin#sakura.ne.jp')->from('emailconf#.ne.jp')->subject('you got order');});
$data = session()->regenerateToken();
return view('mail.complete');
}
I am sending base64 image along with some form data from postman to laravel 5 with mysql. The code works well and returns the success json as well. All values from json is stored in mysql but the json image path is not stored in database, instead some code is stored in databse.
My actual json response in postman is =>
{"success":{"userid":"4","fname":"s","lname":"s","img":"uploads\/5a3f6218a1ed0.jpg"}}
All above json values are stored in databse but the img json path is not stored, instead following data is stored in database.
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs
My Laravel API code is
public function add(Request $request)
{
$validator = Validator::make($request->all(), [
'userid' => 'required',
'fname' => 'required',
'lname' => 'required',
'img' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$user = News::create($input);
$success['userid'] = $user->userid;
$success['fname'] = $user->fname;
$success['lname'] = $user->lname;
if ($user->img)
{
$img2 = $user->img;
$img3 = str_replace('data:image/jpg;base64,', '', $img2);
$img3 = str_replace(' ', '+', $img3);
$data = base64_decode($img3);
$file = 'uploads/' . uniqid() . '.jpg';
file_put_contents($file, $data);
$imgfile = $file;
$success['img'] = $imgfile;
}
return response()->json(['success'=>$success], $this->successStatus);
}
What actually i am missing...
This is because you save record like this:
$user = News::create($input);
so you don't save $imgfile in database.
You can add after:
$success['img'] = $imgfile;
the following line to update record
$user->update(['img' => $imgfile]);
or you can change the order of your code to create News record later with valid img field already.
Also keep in mind you are using wrong variable names. There is no point to have $user variable that holds News model.
As Marcin has stated above it's because you're not saving imgfile into the database.
I would also consider refactoring some of your code so that the add method isn't so verbose. Consider something like the following code block. Please note no use statements have been used an no try/catch has been implemented.
I have also found that it is generally better to give fuller variable and property names. Such as fname I would call first_name/firstName depending on context.
<?php
class ApiController
{
/**
* Add news item
*
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function add(Request $request)
{
$validator = $this->validateData($request);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 422);
}
$news = News::create($request->all());
if ($news) {
$success['userid'] = $news->userid;
$success['fname'] = $news->fname;
$success['lname'] = $news->lname;
$success['img'] = $this->uploadImage($news);
$news->update(['img' => $success['img']]);
return response()->json(['success'=>$success], $this->successStatus);
}
return response()->json(['error'=>'An Error occurred when creating the news item'], 422);
}
/**
* Upload Image and return file name
*
* #param $news
* #return string
*/
protected function uploadImage($news)
{
$image = $news->img;
$image = str_replace('data:image/jpg;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$file = 'uploads/' . uniqid() . '.jpg';
file_put_contents($file, $data);
return $file;
}
/**
* Validate inbound request
*
* #param $request
*/
protected function validateData($request)
{
Validator::make($request->all(), [
'userid' => 'required',
'fname' => 'required',
'lname' => 'required',
'img' => 'required',
]);
}
}
I have this function which will allow users to upload one image or more. I already create the validation rules but it keep returning false no matter what the input is.
Rules :
public function rules()
{
return [
'image' => 'required|mimes:jpg,jpeg,png,gif,bmp',
];
}
Upload method :
public function addIM(PhotosReq $request) {
$id = $request->id;
// Upload Image
foreach ($request->file('image') as $file) {
$ext = $file->getClientOriginalExtension();
$image_name = str_random(8) . ".$ext";
$upload_path = 'image';
$file->move($upload_path, $image_name);
Photos::create([
'post_id' => $id,
'image' => $image_name,
]);
}
//Toastr notifiacation
$notification = array(
'message' => 'Images added successfully!',
'alert-type' => 'success'
);
return back()->with($notification);
}
How to solve this ?
That's all and thanks!
You have multiple image upload field name like and add multiple attribute to your input element
<input type="file" name="image[]" multiple="multiple">
So that, your input is like array inside which there will be images.
Since there is different method for array input validation, see docs here.
So, you have to validate something like this:
$this->validate($request,[
'image' => 'required',
'image.*' => 'mimes:jpg,jpeg,png,gif,bmp',
]);
Hope,You understand
I'm working on a website with Laravel and I have the registration and login forms on the same page. The only problem is that if I type the wrong password on the login form the error will show on both forms below the password input.
I've googled this and I have seen some other people with this problem but they are all working on a version below 5.4 and all those solutions are different in version 5.4. Does anyone know what exactly I need to change to make this work?
So far I've changed the names in the forms to 'login_password' and 'register_password', but this only gives me errors.
If you're going to go down the route of changing the input names you'll need to update your LoginController and RegisterController.
Login Controller
You will need to add the following:
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required', 'login_password' => 'required',
]);
}
protected function credentials(Request $request)
{
return [
$this->username() => $request->input($this->username()),
'password' => $request->input('login_password'),
];
}
RegisterController (these methods should already exist in the controller, you'll just need to update password to register_password where applicable)
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'register_password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['register_password']),
]);
}
You will also need to include the Request by putting the following at the top of the file with the other use statements:
use Illuminate\Http\Request;
Hope this helps!
So I am trying to group all my validation rules into its respective files in folders for easy maintenance. Below is how my folder structures look:
Project
--app
--config
--(more folders)
--domains
----App
--------Entities
--------Repositories
--------Services
--------Validators
----Core
--------Validators
So what I wanted to achieve is under Core\Validators I created a LaravelValidator.php which look like this
<?php namespace Core\Validators;
use Validator;
abstract class LaravelValidator {
/**
* Validator
*
* #var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Validation data key => value array
*
* #var Array
*/
protected $data = array();
/**
* Validation errors
*
* #var Array
*/
protected $errors = array();
/**
* Validation rules
*
* #var Array
*/
protected $rules = array();
/**
* Custom validation messages
*
* #var Array
*/
protected $messages = array();
public function __construct(Validator $validator)
{
$this->validator = $validator;
}
/**
* Set data to validate
*
* #return \Services\Validations\AbstractLaravelValidator
*/
public function with(array $data)
{
$this->data = $data;
return $this;
}
/**
* Validation passes or fails
*
* #return Boolean
*/
public function passes()
{
$validator = Validator::make(
$this->data,
$this->rules,
$this->messages
);
if ($validator->fails())
{
$this->errors = $validator->messages();
return false;
}
return true;
}
/**
* Return errors, if any
*
* #return array
*/
public function errors()
{
return $this->errors;
}
}
Then in my App\Validators I created a file name RegistrationFormValidator.php which look like this
<?php namespace App\Validators\Profile;
class RegistrationFormValidator extends \Core\Validators\LaravelValidator
{
protected $rules = array(
'first_name' => 'required',
'last_name' => 'required',
'username' => 'required',
'password' => 'required',
'rTPassword' => 'required',
'profile_url' => 'required',
'email' => 'required|email',
'gender' => 'required',
'dob' => 'required',
);
}
so usually in laravel 4.2, to validate something all i do is construct the validation rules and then call it in services which look like this
<?php namespace App\Services\Profile;
/*
|-----------------------------------------------------------
| This section injects the repositories being used
| in this service.
|-----------------------------------------------------------
*/
use App\Repositories\Profile\ProfileRepository;
use Core\ValidationFailedException;
use App\Validators\Profile\RegistrationFormValidator;
use Validator;
class ProfileService implements ProfileServiceInterface
{
protected $_profile;
protected $v;
/*
|-----------------------------------------------------------
| All construsted models variables must carry
| the '_' sign to identify it as a model variable
|-----------------------------------------------------------
*/
public function __construct(ProfileRepository $_profile, RegistrationFormValidator $v)
{
$this->_profile = $_profile;
$this->v = $v;
}
/*
|-----------------------------------------------------------
| 1. All try and catch error handling must be done
| in the respective controllers.
|
| 2. All data formattings must be done in this section
| then pass to repository for storing.
|
| 3. No controller actions allown in this section
|-----------------------------------------------------------
*/
public function createProfile($array)
{
if($this->v->passes())
{
//save into db
}
else
{
throw new ValidationFailedException(
'Validation Fail',
null,
$this->v->errors()
);
}
}
}
But the problem is once i upgraded into laravel 5 i did the same thing and when i try to execute the code it returns me with this error
ErrorException in ProfileService.php line 26:
Argument 2 passed to App\Services\Profile\ProfileService::__construct() must be an instance of App\Validators\Profile\RegistrationFormValidator, none given
My code works absolutely fine in L4.2 but once i upgraded it wont work anymore. I also know that i can do validation like such
public function createProfile($array)
{
$v = Validator::make($array, [
'first_name' => 'required',
'last_name' => 'required',
'username' => 'required',
'password' => 'required',
'rTPassword' => 'required',
'profile_url' => 'required',
'email' => 'required|email',
'gender' => 'required',
'dob' => 'required',
]);
if($v->passes())
{
}
else
{
throw new ValidationFailedException(
'Validation Fail',
null,
$v->errors()
);
}
}
But the problem is if i would have more validation rules or scenario it will flood the whole service file.
Any suggestions or solutions that will guide me? thanks in advance!
In Laravel 5 you have something similar, which handles better the validation and makes validation clean and easy. It is called Form Request Validation. The idea there is the same - to have different classes that handle validation in different scenarios.
So whenever you need a validation you can create new FormRequest, like this:
php artisan make:request RegisterFormRequest
A new class will be generated under app/Http/Requests. There you can see it has two methods authorize and rules. In the first one you can make a check if given user is allwed to make this request. In the second method you can define your rules, just like in the validator.
public functions rules() {
return array(
'first_name' => 'required',
'last_name' => 'required',
'username' => 'required',
'password' => 'required',
'rTPassword' => 'required',
'profile_url' => 'required',
'email' => 'required|email',
'gender' => 'required',
'dob' => 'required',
);
}
Then you can change your controller method like this:
public function postCreateProfile(RegisterFormRequest $request) {
// your code here
}
The are a few cool things here. First one - the class will be automatically constructed in injected in your controller method by the IoC container, you don't need to do something special. The second cool thing is that the validation check is done before the Request object is passed to the controller, so if any validation error occurs you will be redirected back with all errors according to your rules set. This means that writing your code in the postCreateProfile method you can assume if this code get executed the validation is passed at this position and no additional check are needed by you.
I suggest you to migrate your code to use Laravel 5 Form Requests, because what you need is already implemented in the framework, and yes basically this is the point of the migration of one version to another. You can also check the documentation for more examples.