I'm trying to post an image from a one to many relationship while also doing the CRUD (create part), but I am having some trouble doing it. I keep on getting this error,Call to a member function getClientOriginalName() on array, whenever I try to use associate to define the relationship together with user_info with user_image table. So what should I do?
Here are my codes:
createController:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($file = $request->hasFile('input_img')) {
$file = array();
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
#foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->signature !!}">
#endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
I think you have a problem inside store1() method. You sould not re-declare $file.
if($file = $request->hasFile('input_img')) {
$file = array();
$fileName = $file->getClientOriginalName();
Instead get the file using the file() method:
if($request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalName();
See more on the Laravel's requests documentation.
Read through your logic in the store1 method again... You are setting the $file variable to an empty array and then trying to call the getClientOriginalName() method on it:
$file = array();
$fileName = $file->getClientOriginalName();
i use this in laravel 9
$allFile =count($request->files);
for($i=0; $i<$allFile; $i++){
dd($request->files[$i].getClientOriginalName());
}
Related
I am Learning at the moment. But got one problem. I have build a database:
and my controller code is:
UploadController.php
public function upload(Request $request, Task $task)
{
$task->image = Request::get('image');
$task->save();
return redirect('/');
}
TaskController.php
public function update(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->description = Request::get('description');
$task->save();
return redirect('/');
}
}
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->image = Request::get('image');
$task->save();
return redirect('/');
}
}
edit.blade.php
<div class="container">
<h1>Edit the Task</h1>
<form method="POST" action="/task/{{ $task->id }}">
<div class="form-group">
<textarea name="description" class="form-control">{{$task->description }}</textarea>
</div>
<form action="{{ URL::to('upload') }}" method="post" enctype="multipart/form-data">
<label>Select image to upload:</label>
<input class="btn btn-primary" type="file" name="file" id="file">
<input class="btn btn-primary" type="submit" value="Insert" name="insert" enctype="multipart/form-data">
<input class="btn btn-primary" type="hidden" value="{{ csrf_token() }}" name="_token">
<img class="user_avatar" src="{{url('public/uploads/test.jpg')}}">
</form>
<div class="form-group">
<button type="submit" name="update" class="btn btn-primary">Update task</button>
</div>
<div class="form-group">
<button type="submit" name="update" class="btn btn-primary">Update task</button>
</div>
These are my code, when I try to insert an image in to my database, it become null and self create another set of null data. How can I fix this problem? Thank you.
This is my database at the moment
This is the inside value of the image
Try this
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->image = \Storage::disk('public')->put('image', $request->file('image'));
$task->save();
return redirect('/');
}
}
and
filesystems.php
inside
'public' => [
'driver' => 'local',
'root' => public_path() . '/uploads',
'url' => env('APP_URL').'/uploads',
'visibility' => 'public',
],
inside blade
<input class="btn btn-primary" type="file" name="image" id="file">
change name="image" then only you can get $request->file('image')
Use this to same image directly to db in BLOB field
$task->image = request('image')->encode('jpg', 80);
$task->save();
You can update the variables as suitable to you but the solution is in encode
You can encode your image first like this
$b64 = base64_encode(request('image'));
you can not save image in database, you must move image to a folder and save address it in database and type column image must be varchar text.
change code to :
public function storeTask()
{
$task = new Task();
$task->name = request('name');
$task->description = request('description');
$image = request->file('image');
$extention = $image->getClientOriginalExtension();
$name = rand(1000, 9999) '.' . $extention;
$path = public_path() . '/images/' . $name;
$image->move($path);
$task->image = $path;
$task->save();
return redirect('/task');
}
Try the following code:
$path = $request->file('image')->getRealPath();
$image = file_get_contents($path);
$base64 = base64_encode($image);
$task->image = $base64;
$task->save();
I'm working to make a multi upload image to database with intervention resizer in Laravel.
This is what I'm coding right now in my controller
imgProdukProc controller:
use Illuminate\Http\Request;
use File;
use Image;
use App\imgProd;
.....
public function store(Request $request)
{
if($request->hasFile('img')){
foreach ($request->file('img') as $image) {
if ($image->isValid()) {
$img = new imgProd();
$image_name = uniqid() .'.'. $image->getClientOriginalExtension();
$path = public_path('/img/prod');
$imgx = Image::make($image->getRealPath());
$imgx->resize(360, 360, function ($constraint) {
$constraint->aspectRatio();
})->save($path.'/'.$image_name);
$img->id_prod = $request->get('id_prod');
$img->pics = 'img/prod/'.$image_name;
$date=date_create('now');
$format = date_format($date,"Y-m-d");
$img->date = $format;
$img->save();
return redirect('adminImgProd')->with('success', 'Picture successfully added ');
}
}
}
}
and this is my views
adminImgProd Views
<form enctype="multipart/form-data" action="{{url('adminImgProd')}}" method='post'>
#csrf
<div class="form-group">
<label>CODE PRODUCT</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-pencil"></span></span>
<input type="text" autocomplete="off" class="form-control" id='id_prod' name='id_prod' required="required" />
<span class="input-group-addon"><button type="button" onClick="javascript:openWindow2();">Select</button></span>
</div>
</div>
<div class="form-group">
<label>IMAGE PRODUCT</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-pencil"></span></span>
<input multiple type="file" class="form-control" name='img[]' id='file-input' required="required" /></div>
</div>
Code above is working , but somehow when I tried to upload 2 images or 3 images the only image saved both in target folder and in database is only one and it is the last one
Where is my code mistake , or just my code simply wrong from the start ?
Thank you in advance
You put your return in your foreach, so after 1 loop, it will return and exit your function :
public function store(Request $request)
{
if ($request->hasFile('img')){
foreach ($request->file('img') as $image) {
if ($image->isValid()) {
$img = new imgProd();
$image_name = uniqid() .'.'. $image->getClientOriginalExtension();
$path = public_path('/img/prod');
$imgx = Image::make($image->getRealPath());
$imgx->resize(360, 360, function ($constraint) {
$constraint->aspectRatio();
})->save($path.'/'.$image_name);
$img->id_prod = $request->get('id_prod');
$img->pics = 'img/prod/'.$image_name;
$date=date_create('now');
$format = date_format($date,"Y-m-d");
$img->date = $format;
$img->save();
}
}
return redirect('adminImgProd')->with('success', 'Picture successfully added ');
}
}
You can do the following for multiple images:
$images = $request->file('images');
foreach ($images as $key => $image) {
if ($request->hasFile('images') && $request->file('images')[$key]->isValid()) {
$path = $request->images[$key]->store('public/images');
$path = basename($path);
$image = new ProductImages();
$image->product_id = $request->get('product_id');
$image->photo = $path;
$image->save();
}
}
I hope it would helpful.
I have a Tag.php model which has hasMany relationship with the Image.php model. I already have a working images and tags tables, however, I am not sure how to make the image_tag table be automatically filled when I upload an image with a certain tag. If I were using vanilla PHP, I would insert the image first, then get its id, get the id of the tag and then make a second insert into the image_tag table. This is my code:
Upload view:
#extends('layouts.app')
#section('content')
<div class="wrapper">
<div class="main">
<div class="formContainer">
<form action="{{ route('imageUpload') }}" method="POST" enctype="multipart/form-data">
<label for="name">Name</label>
<input class='contactInput' type="text" name="name" placeholder="Image Name">
<label for="description">Description</label>
<input class='contactInput' type="text" name="description" placeholder="Description">
<label for="description">Tag</label>
<select class='tagSelect' name='tags'>
#foreach($tags as $tag)
<option value='{{$tag->name}}'>{{$tag->name}}</option>
#endforeach
</select>
<input type="file" name="image">
{{ csrf_field() }}
<button class='contactSubmit' type="submit" name="submit">UPLOAD</button>
</form>
</div>
</div>
</div>
#endsection
uploadImage function from my ImagesController:
class ImagesController extends Controller
{
public function uploadImage(Request $request){
$this->validate($request, [
'name' => 'required|max:120',
'description' => 'max:120|nullable',
'image' => 'required|max:1999'
]);
$name = $request['name'];
$description = $request['description'];
$tag = $request['tags'];
$userId = auth()->user()->id;
$file = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($file, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$path = $request->file('image')->storeAs('public/images/uploaded', $fileNameToStore);
$image = new Image();
$image->name = $name;
$image->description = $description;
$image->user_id = $userId;
$image->file_name = $fileNameToStore;
$image->save();
return redirect()->route('home');
}
Well you are going all wrong.
your relation is Many to Many
so in your Tag model you should do
public function images()
{
return $this->belongsToMany(Image::class, 'your pivot table name in this case image_tag ','tag_id','image_id');
}
and in Image model
public function tags()
{
return $this->belongsToMany(Tag::class, 'your pivot table name in this case image_tag ','image_id','tag_id');
}
then you can save an image and attach tags like this
$image->tags()->attach($tags)
which $tags is an array of ids like [1,2,3,4,5,6]
$image = new Image();
$image->name = $name;
$image->description = $description;
$image->user_id = $userId;
$image->file_name = $fileNameToStore;
$image->save();
$image->tags()->attach($tags);
hope it helps
I made a method which allows the user to update their profile picture. I also added a function which deletes their old profile picture if they update to a new one. But i get an error saying Call to undefined method Intervention\Image\File::delete().
What is causing this? In the code below it makes perfect sense for me. I hope you guys can help. Thanks in advance
Code:
UserController.php
public function update_avatar(Request $request) {
$this->middleware('auth');
if ($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = Auth::user()->username . time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->fit(300,300)->save( public_path('/uploads/avatars/' . $filename));
$user = Auth::user();
$user->avatar = $filename;
$user->save();
//Verwijderd vorige foto
if ($user->avatar != 'default.jpg') {
$path = 'uploads/avatars/';
$lastpath = Auth::user()->Avatarpath;
File::delete(public_path($path . $lastpath));
}
}
return view('user.profile', array('user' => Auth::user()));
Route: Route::post('{username}/profile', 'UserController#update_avatar');
The form that is supposed to do this.
<div class="row">
<div class="col l12 m12 s12">
<div class="card">
<div class="card-content">
<form enctype="multipart/form-data" action="profile" method="POST">
<input type="file" name="avatar">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="pull-right btn btn-primary" value="Change profile">
</form>
</div>
</div>
</div>
</div>
Changing the picture works just fine. If I reload the page the profile picture is updated but it doesn't delete the old one.
try this. does this help.
public function update_avatar(Request $request) {
$this->middleware('auth');
if ($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = Auth::user()->username . time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->fit(300,300)->save( public_path('/uploads/avatars/' . $filename));
$user = Auth::user();
$user->avatar = $filename;
$user->save();
//Verwijderd vorige foto
if ($user->avatar != 'default.jpg') {
$path = public_path('uploads'.DIRECTORY_SEPARATOR.'avatars'. DIRECTORY_SEPARATOR.Auth::user()->Avatarpath);
if (file_exists($path)) {
unlink($path);
}
}
}
return view('user.profile', array('user' => $user));
}
I was trying three images in three different fields in database..for that I was following method in controller.But the problem I'm facing is though i have three input fields it stored only two images with same name in the public folder and in database it stored value like 1 (for product_image), 4 ( for vendor_image), 9 (for user_image).
How do i properly stored the images in public folder as well as database..thanks in advance .
Here is the controller:
public function store(Request $request)
{
$product = new Product();
$files= [];
if($request->file('product_image')) $files[] = $request->file('product_image');
if($request->file('vendor_image')) $files[] = $request->file('vendor_image');
if($request->file('user_image')) $files[] = $request->file('user_image');
foreach($files as $file)
{
if(!empty($file))
{
$filename = time().'.'.$file->getClientOriginalExtension();
$file->move('images/',$filename);
}
}
$product->product_image = $filename[0];
$product->vendor_image = $filename[1];
$product->user_image = $filename[2];
$product->save();
}
here is the View part :
<div class="form-group">
<label>Product Image</label>
<input type="file" name="product_image" id="product_image" width="200px">
</div>
<div class="form-group">
<label>Feature Image</label>
<input type="file" name="vendor_image" id="vendor_image" width="200px">
</div>
<div class="form-group">
<label>Slurp Image</label>
<input type="file" name="user_image" id="user_image" width="200px">
</div>
public function imageupload(Request $request) {
$files=[];
if($request->file('profilePhoto')) $files[]=$request->file('profilePhoto');
if($request->file('fssaiPhoto')) $files[]=$request->file('fssaiPhoto');
if($request->file('panPhoto')) $files[]=$request->file('panPhoto');
foreach($files as $file){
$uniqid = Str::random(9);
$fileName = $uniqid.'.'.$file->extension();
$file->move(public_path('file'), $fileName);
$data[]=$fileName;
}
$images=new fileuploadmodels;
$images->phno=$request->phno;
$images->profilePhoto=$data[0];
$images->fssaiPhoto=$data[1];
$images->panPhoto=$data[2];
$images->save();
return response()->json([
"message"=>"photo upload success"
],201);
}
Try this:
$product_image = NULL;
$vendor_image= NULL;
$user_image= NULL;
if($request->product_image)
{
$product_image= time().'-'. $request->product_image->getClientOriginalName();
$request->product_image->move(public_path('images/'),$product_image);
}
if($request->vendor_image)
{
$vendor_image= time().'-'. $request->vendor_image->getClientOriginalName();
$request->vendor_image->move(public_path('images/'),$vendor_image);
}
if($request->user_image)
{
$user_image= time().'-'. $request->user_image->getClientOriginalName();
$request->user_image->move(public_path('images/'),$user_image);
}
$product->product_image = $product_image;
$product->vendor_image = $vendor_image;
$product->user_image = $user_image;
$product->save();