How to insert multiple images in a table? - laravel-5

How to insert multiple images into the table?
Controller
public function save(Request $request)
{
$images = new Image;
$input = $request->file("image");
if($files=$request->file('image')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move(public_path("/images/"),$name);
$images[]=$name;
$images->Image = $input->getClientOriginalName();
}
}
$images->save();
$image = Image::find($request->id);
return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}
I expect to insert images into database, the the error is No message

I think it's better to use mass assignment to insert your image name into the database. The code will be like this :
public function save(Request $request)
{
$images = new Image;
if ($files = $request->file('image')) {
foreach ($files as $file) {
$name = $file->getClientOriginalName();
$file->move(public_path("/images/"),$name);
$images->create(['Image' => $file]);
}
}
return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}
You must insert it in every loop, if you use the model attribute it will just change every time the loop sets the image name.

public function create(Request $request)
{
$rules = array(
'gallery_album_id'=> 'required',
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
);
$input=$request->all();
$image=array();
if($files=$request->file('image')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('images',$name);
$image=$name;
gallery::insert( [
'image'=> $image,
'gallery_album_id' =>$input['gallery_album_name']
]);
}
}
return redirect()->route('gallery')->withStatus(__('Album successfully added.'));
}

Related

Laravel: How to return JSON response when using foreach

I am uploading images using Vue and my Laravel backend endpoint looks like this below. I am unsure of what to put in the response though since it is a foreach that iterates through each file and uploads them but I still want to return the response as JSON.
public function upload(Request $request)
{
$files = $request->file('images');
foreach ($files as $file) {
Storage::put('store/assets/', file_get_contents($file->getRealPath()), ['visibility' => 'public']);
}
return response()->json(????);
}
public function upload(Request $request)
{
$files = $request->file('images');
$stack = [];
foreach ($files as $file) {
$fileName = Storage::put('store/assets/', file_get_contents($file->getRealPath()),
['visibility' => 'public']);
array_push($stack, $fileName);
}
return response()->json($stack);
}
Or you can just do like that:
$data = ["success" => 1];
return response()->json($data);
My offer:
if your query is executed succesfully
$data=[
"stat"=>1,
"data"=>[
"first"=>1,
...
]
]
else
$data=[
"stat"=>0,
"error"=>"Not successfull"
]

Data not inserted to Mysql using Eloquent laravel

I have problem with insert data to Database table using Eloquent Model insert() method in Larvel. But when I click on submit button then data not inserted in database.
Here is my implemented code:-
Controller
public function receivedAll(Request $request, ItemPR $item_code)
{
$item_code = $request->item_code;
$pr_qty = $request->pr_qty;
$uploadFile = $request->file('file_document');
$update_data = ItemPR::whereIn('item_code', explode(",", $item_code))->update(['receive'=> 'received']);
$get_data = ItemPR::whereIn('item_code', explode(",", $item_code))->orWhereIn('pr_qty', explode(",", $pr_qty))->get();
$data = [];
foreach($get_data as $value) {
if(is_array($uploadFile)) {
foreach($uploadFile as $file) {
$filename = $file->getClientOriginalName();
$folder[] = $file->storeAs('uploads', $filename);
}
$data[] =
[
'item_code' => $value->item_code,
'qty' => $value->pr_qty,
'file_document' => $filename,
'created_at' => Carbon::now(),
'created_by' => Auth::user()->nick_name,
'last_update' => Carbon::now(),
'last_update_by' => Auth::user()->nick_name,
];
}
WarehouseInventory::insert($data);
}
// Model elequent insert
return response()->json(['success'=>"Products Updated successfully."]);
}
Model:- WarehouseInventory.php
class WarehouseInventory extends Model
{
protected $table = 'warehouse_inventori';
protected $primaryKey = 'pr_item';
public $incrementing = false;
const CREATED_AT = 'created_at';
const UPDATED_AT = 'last_update';
protected $fillable = [
'pr_item', 'item_code', 'qty', 'po_number', 'warehouse_id', 'file_document', 'created_at', 'last_update', 'last_update_by', 'created_by'
];
}
Any idea or what's in my code is wrong?
You are using insert() method on eloquent, insert() is the method of DB class, Eloquent has create() method instead,
WarehouseInventory::create($data);
src: https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models

Not updating database and not throwing error in laravel

I have an issue while updating the user. When I try to update the user after clicking the save button then it redirect me to the same page and not throwing me any error but also its not updating anything in the database. Below is my code. I have no idea what's going on here. Help me :)
Controller
public function update(ReportRequest $request, $id)
{
$report = Report::findOrFail($id);
$input = $request->all();
if ($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file' => $name]);
$input['photo_id'] = $photo->id;
}
$report->update($input);
return redirect()->back();
}
Route
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
'edit'=>'admin.reports.edit',
]]);
Models
class Report extends Model
{
protected $fillable = [
'student_id',
'student_name',
'class_id',
'subject',
'teacher_name',
'report_categories_id',
'total_marks',
'obtained_marks',
'percentage',
'position',
'photo_id',
];
public function photo() {
return $this->belongsTo('App\Photo');
}
public function studentsClass() {
return $this->belongsTo('App\StudentsClass', 'class_id');
}
public function student() {
return $this->belongsToMany('App\Student');
}
}
Make sure you have your $fillable properties in your Photo and Report models, otherwise the create() and update() methods won't work as expected.
Check the $fillable fields in the Model as above. If the error persists check your laravel log on storage/logs/laravel.log.
In controller:
public function update(ReportRequest $request, $id){
$report = Report::findOrFail($id);
$input = $request->all();
try{
if ($request->photo_id != '') {
$path = 'images/';
$file = $request->photo_id;
$name = time() . $file->getClientOriginalName();
$file->move($path, $name);
$photo = Photo::create(['file' => $name]);
$report->update(['photo_id' => $photo->id]);
}
return redirect()->back();
}catch(\Exception $e){
return redirect()->back()->with('error_message', $e->getMessage());
}
}

Laravel-api for multiple file upload

I want to make laravel api for multiple file upload when i am uploading then its gives error $data is undefined variable.please help me how to remove this error..?
FileUploadController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Detail;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
class FileUploadController extends Controller
{
public function uploadFile(Request $request){
$this->validate($request, [
'user_sharing_image' => 'required',
'user_sharing_image.*' => 'mimes:doc,pdf,docx,zip'
]);
if($request->hasfile('user_sharing_image'))
{
foreach($request->file('user_sharing_image') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[] = $name;
}
}
$file= new Detail();
$file->title = $request->title;
$file->info = $request->info;
$file->user_id = $request->user()->id;
$file->user_sharing_image=json_encode($data);
$file->save();
return back()->with('success', 'Data Your files has been successfully added');
}
}
I am using laravel passport for auth and want to store user_id but do not geting please help me how to resolve both problem from this code
Give it a try
$data = [];
if($request->hasfile('user_sharing_image'))
{
foreach($request->file('user_sharing_image') as $key=>$file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[$key] = $name;
}
}
$file= new Detail();
$file->title = $request->title;
$file->info = $request->info;
$file->user_id = Auth::user()->id;
$file->user_sharing_image=json_encode($data);
$file->save();
You are getting this error because $data is not defined.
Before foreach loop you can declare it as $data = array();
i think you should use files method to return array of files :
foreach($request->files('user_sharing_image') as $file)
Hello fellow developers
This will work properly
$files = $request->allFiles('imgs');
foreach ($files as $key => $img) {
# code...
$filename = request()->getSchemeAndHttpHost() . '/assets/images/users/upload/profile/photos/' . time() . '.'. $img->extension();
$img->move(public_path('/assets/images/users/upload/profile/photos/'), $filename);
$photos = UserPhoto::create([
'user_id' => $user->id,
'name' => $filename
]);
}
return response()->json([
'status' => true,
'data' => 'Photos Uploaded Successfully!!'
]);

Laravel - update one to one field

I have an update post form, where I need to update the name of the post in posts table and the associated text within the text table. I can't seem to get it to work at all.
Model - Post.php
public function text()
{
return $this->hasOne('Text');
}
Model - Text.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function updateQuestionForm($id)
{
$post = Post::find($id);
$input = Input::all();
$rules = array(
'text' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::back()->withErrors($validation)->withInput();
} else {
$post->title = Input::get('title');
$post->save();
$text = $post->text();
$text->text = Input::get('text');
$post->text()->save($text);
$message = "Post updated";
return Redirect::to('question/'.$post->id.'/'.$post->slug.'/')->with('message', $message);
}
}

Resources