Save image path to BD - Laravel 5.8 - laravel

I am making a form in laravel 5.8 in which I am trying to save the image in a folder and the path in the database.
But just save the image and not the route, I've been searching and haven't found a solution.
The "uploads" folder (folder where images are saved) is located inside the "public" folder.
This is my controller:
public function store(SaveAssistanceRequest $request)
{
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$name = time().$file->getClientOriginalName();
$file->move(public_path().'/uploads/', $name);
}
$assistance= new Assistance();
$assistance->photo = $name;
Assistance::create($request->validated());
return redirect()->route('assistances.index')->with('status',' Assistance was created successfully.
');
}
This file validates the data
class SaveAssistanceRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'resident_id' => 'required',
'date' => 'required',
'entry_time' => 'required',
'departure_time' => 'required',
];
}
public function messages()
{
return[
'resident_id.required' => 'Assistance needs a resident',
'date.required' => 'Assistance needs a date',
'entry_time.required' => 'Assistance needs one hour of entry',
'departure_time.required' => 'Assistance needs a departure time',
];
}
}
Can anybody help me?

public function store(SaveAssistanceRequest $request)
{
$name='';
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$name = time().$file->getClientOriginalName();
$file->move(public_path().'/uploads/', $name);
}
$assistance=Assistance::create($request->validated());
$assistance->photo = $name;
$assistance->save();
return redirect()->route('assistances.index')->with('status',' Assistance was created successfully.

Related

Laravel Excel: How can I read Excel file and save in the database with relationship of quiz_id in quiz_information table

I'm planning to import a quiz question and choices using excel but it has relationship to the other table. I need to get the id of the quiz_information and create the record using an api. My problem is that when I tried to create the record my plan is to input the id first of the quiz_information and then import the excel file. the quiz_id(id of the quiz_information) the number of records I have on the file should have the same quiz_id.
Sample image of my postman:
This is my controller
class QuizImportController extends Controller
{
public function show()
{
return view('quiz_questions.import');
}
public function store(Request $request){
$rules=[
'quiz_id' => 'required',
'file' => 'required|mimes:csv,xlx,xls,xlsx'
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()){
return response()->json($validator->errors(),400);
}
$data = $request->validate([
'quiz_id' => 'required',
]);
$file = $request->file('file');
Excel::import(new QuizImport, $file);
$quizQuestions = quizQuestions::create($data);
return response(['message'=>"Quiz successfully imported",
'error'=>false,
'error code'=>200,
'line'=>"line".__LINE__."".basename(__LINE__),
'file'=>$file],200,[],JSON_NUMERIC_CHECK);
}
}
This is my QuizImport
public function collection(Collection $rows)
{
foreach($rows as $row){
$quizQuestions = quizQuestions::create([
'question_num' => $row['question_num'],
'question_content' => $row['question_content'],
'tagalog_question'=> $row['tagalog_question'],
]);
$quizQuestions->choices()->create([
'option' => $row['option'],
'remarks' => $row['remarks'],
'tagalog_choices'=> $row['tagalog_choices'],
]);
}
}
public function rules(): array
{
return [
'question_content' => 'required|distinct:*.question_content',
];
}
}
My Excel file has a heading row of question_num,question_content,tagalog_question,option, tagalog_choices, and remarks.
The output should be like this:

How can i avoid image required in edit form if image exist in laravel?

I am adding and editing a user with same function (Store), when ever i add a user it asks me image is required but whenever i edit a user which have image it also ask me image is required and i want if a image is already present it wont ask me , please see my above code i had recently changed my code according to Gurpal singh
In my controller
public function rules()
{
$child_details = Children::findOrFail($inputs['id']);
$rules = [
'child_name' => 'required',
'gender' => 'required',
'dob' => 'required',
'current_class' => 'required',
'b_group' => 'required',
'm_tongue' => 'required',
'image' => 'image',
];
if ($child_details->notHavingImageInDb()){
$rules['image'] = 'required|image';
}
return $rules;
}
public function Postchild(Request $request)
{
$data = \Input::except(array('_token')) ;
$validator = \Validator::make($data,$rules);
$inputs = $request->all();
if ($validator->fails())
{
return redirect()->back()->withInput()->withErrors($validator->messages());
}
if(!empty($inputs['id'])){
$child_details = Children::findOrFail($inputs['id']);
}else{
$child_details = new Children;
}
$child_details->parent_id = Auth::User()->id;
$child_details->child_name = $inputs['child_name'];
$child_image = $request->file('image');
if($child_image){
$tmpFilePath = 'uploads/childrens/';
$extension = $child_image->getClientOriginalExtension();
$hardPath = str_slug($inputs['child_name'], '-').'-'.md5(time());
$img = Image::make($child_image);
//$img->resize(180)->save($tmpFilePath.$hardPath.'-b.jpg');
$img->fit(250, 250)->save($tmpFilePath.$hardPath.'.'.$extension);
$child_details->image = $hardPath.'.'.$extension;
}
$child_details->save();
if(!empty($inputs['id'])){
return \Redirect()->route('child_list')->with('success', 'Child has been updated');
}else{
return \Redirect()->route('child_list')->with('success', 'Child has been added');
}
}
You can use Conditionally Adding Rules Not having image in database
Add this in model
public function notHavingImageInDb()
{
return (empty($this->image))?true:false;
}
This is the validation rule request
public function rules()
{
$user = User::find(Auth::id());
$rules = [
'name' =>'required|max:100',
'image' =>'image',
];
if ($user->notHavingImageInDb()){
$rules['image'] = 'required|image';
}
return $rules;
}
Don't forgot to import auth and user model
ie
use App\User;
use Auth;
for more detail click here
You can normally do like below :
$rule = array(
'name' => 'required',
);
if (!empty($inputs['id'])) {
$user = User::findOrFail($inputs['id']);
} else {
$rule["image"] = "required";
$user = new User;
}
It is better to separate them or simply create another function. But you can put an if statement that if the image is in the request or not.
Like this:
if(! isset($data['image'])){ //if the image is not in the request
//Your code
}
else{ //if the image is in the request
//Your code
}
If you want a code for storing, renaming, moving an image feel free to request.
You can use validation's after hook.
public function Postchild(Request $request)
{
//Define your rules
$rules = [
'child_name' => 'required',
'gender' => 'required',
'dob' => 'required',
'current_class' => 'required',
'b_group' => 'required',
'm_tongue' => 'required',
];
//Validate your data
$data = $request->except('_token');
$validator = \Validator::make($data,$rules);
$validator->after(function ($validator) {
//Check the mode of request (Create or Update)
if(!empty($data['id'])){
$child_details = Children::findOrFail($data['id']);
if($child_details->image == null){
$validator->errors()->add('image', 'Image field is required');
}
}
});
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
}
Just this few lines can solve your problems... You have to check there image have or not.
Rules in a private or protected function
private function validateRequest($request)
{
//This is for Update without required image, this will check that In DB image have or not
$child_image = Children::find($request->id);
$rules = [];
if ($child_image) :
if ($child_image->image == null):
$rules['image'] = 'required|image|max:1999';
endif;
//This is for regular validation
else :
$rules = [
'image' => 'required|image|max:1999',
];
endif;
return $rules;
}

Validating multiple files in array

I need to validate multiple uploaded files, making sure they are of a specific type and under 2048kb. The below doesn't appear to check all files in the array
'files' and just presumes the posted files of invalid mime type as it seems to be checking the array object and not its contents.
public function fileUpload(Request $request)
{
$validator = Validator::make($request->all(), [
'files' => 'required|mimes:jpeg,jpg,png',
]);
if ($validator->fails())
{
return response()->json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
), 400); }
}
You can validate files array like any input array in Laravel 5.2. This feature is new in Laravel 5.2.
$input_data = $request->all();
$validator = Validator::make(
$input_data, [
'image_file.*' => 'required|mimes:jpg,jpeg,png,bmp|max:20000'
],[
'image_file.*.required' => 'Please upload an image',
'image_file.*.mimes' => 'Only jpeg,png and bmp images are allowed',
'image_file.*.max' => 'Sorry! Maximum allowed size for an image is 20MB',
]
);
if ($validator->fails()) {
// Validation error..
}
Please try this:
public function fileUpload(Request $request) {
$rules = [];
$files = count($this->input('files')) - 1;
foreach(range(0, $files) as $index) {
$rules['files.' . $index] = 'required|mimes:png,jpeg,jpg,gif|max:2048';
}
$validator = Validator::make($request->all() , $rules);
if ($validator->fails()) {
return response()->json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
) , 400);
}
}
we can also make a request and validate it.
php artisan make:request SaveMultipleImages
here is the code for request
namespace App\Http\Requests;
use App\Core\Settings\Settings;
use Illuminate\Foundation\Http\FormRequest;
class SaveMultipleImages extends FormRequest
{
/**
* 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 ['files.*' => "mimes:jpg,png,jpeg|max:20000"];
}
}
and then in controller
public function uploadImage(SaveMultipleImages $request) {
dd($request->all()['files']);
}
Try this way.
// getting all of the post data
$files = Input::file('images');
// Making counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach($files as $file) {
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'uploads';
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
}
}
if($uploadcount == $file_count){
//uploaded successfully
}
else {
//error occurred
}

Problems creating users in laravel

I am creating the traditional register of users with Laravel and I have a problem to send specific value.
public function postUserRegister(){
$input = Input::all();
$rules = array(
'name' => 'required',
);
$v = Validator::make($input, $rules);
if($v->passes() ) {
$user = User::create(Input::all());
} else {
Session::flash('msg', 'The information is wrong');
return Redirect::back();
}
}
This code works correctly , but I need to send always the same value into table users and this column doesn't appear in the form. How can I send the value of the table if the value doesn't appear?
You can just supply the value manually. There are several ways to do this, here is one:
$user = new User(Input::all());
$user->yourcolumn = $yourdata;
$user->save();
You can use input merge to add extra fields.
Input::merge(array('val_key' => $val_name));
$input = Input::all();
Firstly, I think it would be ideal to clean a bit the method, something like that:
public function postUserRegister(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required'
]);
if ($v->fails()) {
Session::flash('msg', 'The information is wrong');
}
User::create($request->all());
return Redirect::back();
}
And now you can simply assign a data to a specific column by using:
$request->merge(['column_name' => 'data']);
The data can be null, or variable etc. And now the whole code would look something like:
public function postUserRegister(Request $request)
{
$request->merge(['column_name' => 'data']);
$validator = Validator::make($request->all(), [
'name' => 'required'
]);
if ($validator->fails()) {
Session::flash('msg', 'The information is wrong');
}
User::create($request->all());
return Redirect::back();
}
You can add whatever data you want directly into the create method:
public function postUserRegister()
{
$input = request()->all();
if (validator($input, ['name' => 'required'])->fails()) {
return back()->with('msg', 'The information is wrong');
}
$user = User::create($input + ['custom' => 'data']);
//
}
P.S. Merging that data into the request itself is a bad idea.
You can do this in the User model by adding the boot() method.
class User extends Model
{
public static function boot()
{
parent::boot();
static::creating(function ($user) {
$user->newColumn = 'some-value';
});
}
...
}
Reference: https://laravel.com/docs/5.2/eloquent#events

Laravel Testing User::store() with phpunit

I'm learning both Laravel and UnitTesting at the moment, so this may be a stupid question.
I'm getting stuck on how to best test the controller function below:
UserController:
public function store()
{
$input = Input::all();
$user = new User($input);
if( ! $user->save()){
return Redirect::back()->withInput()->withErrors($user->getErrors());
}
return Redirect::to('/user');
}
here's the test as I have it so far:
/**
* #dataProvider providerTestUserStoreAddsUsersCorrectly
*/
public function testUserStoreAddsUsersCorrectly($first_name, $last_name, $email, $password)
{
$response = $this->call('POST', 'user', array('first_name'=>$first_name, 'last_name'=>$last_name, 'email'=>$email, 'password'=>$password));
}
public function providerTestUserStoreAddsUsersCorrectly(){
return array(
array("FirstName", "LastName", "Email#add.com", "pass1234")
);
}
This is actually working and adding the user to the db correctly, but I'm not sure how to test the output / what assertions to use as the response should be to add the user to the db and to redirect to the /user page.
How do I finish this test?
If you need to check success status then you can simply send status code from your controller
and check status in test
public function store()
{
$input = Input::all();
$user = new User($input);
if( !$user->save() ){
return array("status"=>'failed');
}
return array("status"=>'success');
}
public function testUserStoreAddsUsersCorrectly($first_name, $last_name, $email, $password)
{
$requested_arr = [
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $password
];
$response = $this->call('POST', 'user', $requested_arr);
$data = json_decode($response ->getContent(), true);
if ($data['status']) {
$this->assertTrue(true);
} else {
$this->assertTrue(false);
}
}

Resources