Question: how i can store the path on table posts-> path
$path = public_path('image').$imageName; doesn't work
Controller
public function store(Request $request)
{
$this->validate(request(),[
'title' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,gif,svg',
'body' => 'required',
]);
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('image'), $imageName);
auth()->user()->publish(
new Post(request(['title','body', 'path']))
);
session()->flash('message', 'your post has now been published');
return redirect('/');
}
This is how i would approach it:
Your validation request was wrong also its not request() see below:
public function store(Request $request, Post $post)
{
$this->validate($request,[
'title' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,gif,svg',
'body' => 'required',
]);
if($files=$request->file('image')){
$path = public_path('path/to/image/folder');
$name= $files->getClientOriginalName();
$files->move($path, $name);
}
$userid = Auth::user()->id;
$post->create([
'user_id' => $userid,
'title' => $request->get('title'),
'body' => $request->get('body'),
'path' => $name (for image)
]);
session()->flash('message', 'your post has now been published');
return redirect()->back();
}
If you'd rather store the path, change $name to $path and it'll save the path for you.
Note: the $request->get() may need to be changed to suit your name=" " fields from the form.
I would do it like this i think it's simpler
try {
$url = 'http://localhost:8000/storage/' . $request->file('picfile')->store('uploads/UserImage', 'public');
} catch (\Exception $e) {
return response()->json([$e->getMessage()], 501);
}
Where "uploads/UserImage" is the folder where it's going tp be stored
And $url i simply the URL
Make sure u form have enctype="multipart/form-data".
php artisan storage:link (this command create a symbolic link
"public/storage" to "storage/app/public" more info here).
Make sure u migration have column to link image. $table->string('image')->nullable();
Check u model post and add image to $fillable (mass assignment,
more info here)
Blade: Acces to img url {{ Storage::url($post->image) }}
I wish I had helped you.
Related
I'm making an edit page for users using Vue + Laravel rest-api and I'm having a hard time linking an image to the image field of the users table.
The first issue is that it's not recognizing the image as a file despite adding enctype="multipart/form-data" to the form. I looked up some solutions, but haven't found something useful.
The console.log(this.form.newimage) results in newimage: "data:image/jpeg;base64,/9j/4AAQS... so I pressume the format of it is good.
Backend UserController:
public function update(Request $request, $id) {
$validatedData = $request->validate([
'name' => 'nullable|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,'.$id,
'phone' => 'nullable|numeric|digits_between:5,15',
'address' => 'nullable|string|max:255',
'postal_code' => 'nullable|numeric|digits_between:3,200',
'country_id' => 'nullable|string|max:255',
'image' => 'nullable',
'newimage' => 'nullable|file',
]);
$data = array();
(...)
if($request->hasFile('newimage')) {
$destination_path = 'public/images';
$avatar = $request->file('newimage');
$imagename = $avatar->getClientOriginalName();
$path = $request->file('newimage')->storeAs($destination_path, $imagename);
$data['image'] = $filename;
}
User::where('id', $id)->update($data);
}
use store file fun
if($request->image)
{
$request->file('image')->store('image','public');
}
I am trying to store logged user's id but I am getting this error
ErrorException
array_map(): Argument #2 should be an array
This is the code in the controller
public function store(Request $request)
{
if (!auth()->check()) {
abort(403, 'Only authenticated users can create new posts.');
}
$data = request()->validate([
'id' => $id = Auth::id(),
'content' => 'required',
'topic' => 'required',
'hashtag' => 'required'
]);
$check = Tweets::create($data);
return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
}
The error is in this line of code.
'id' => $id = Auth::id(),
I know that should be a string but to explain to you what I am trying to do, and I still have not found any solution.
Do it Like this.
public function store(Request $request)
{
if (!auth()->check()) {
abort(403, 'Only authenticated users can create new posts.');
}
$request->validate([
'content' => 'required',
'topic' => 'required',
'hashtag' => 'required'
]);
$data = $request->all();
$data['id'] = Auth::id();
$check = Tweets::create($data);
return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
}
Delete this
'id' => $id = Auth::id(),
and add
$data['id'] = Auth::id();
before
$check = Tweets::create($data);
That should work
Hi im trying to upload image into database when i do this all its gave error like this.
(1/1) BadMethodCallException
Method getClientOrignalName does not exist.
<form action="{{route('post.store')}}" method="post" enctype="multipart/form-data">**strong text**
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required|max:255',
'content' => 'required',
'feature' => 'required|image',
'category_id' => 'required'
]);
// dd($request->all());
//exit;
$featured = $request->feature;
$featured_new_name=time().$featured->getClientOrignalName();
$featured->move('uploads/posts',$featured_new_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'feature'=>'uploads/posts/'. $featured_new_name,
'category_id'=>$request->category_id
]);
Session::flash('success','Post Created Successfully.');
}
You should use file() method for retrieve file information from request. Try this code,
public function store(Request $request) {
$this->validate($request,[
'title' => 'required|max:255',
'content' => 'required',
'feature' => 'required|image',
'category_id' => 'required'
]);
// use file() method for retrive file data
$featured = $request->file('feature');
$featured_new_name = time() . $featured->getClientOrignalName();
$featured->move('uploads/posts', $featured_new_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'feature'=>'uploads/posts/'. $featured_new_name,
'category_id'=>$request->category_id
]);
Session::flash('success','Post Created Successfully.');
}
I have a form where users can edit a branch's info, once the user submits that form, the update() method checks for the validity of the submitted data such as the description must be unique to every subscriber. While the validation WORKS, it doesn't redirect to the exact url/page that I want if the validation fails. It stays in the same edit form.
here's the code of my update() method:
public function update(Request $request, $id)
{
$description = $request->input('description');
$message = $request->input('message');
$subscriber_id = auth()->user()->subscriber_id;
$messages = [
'description.unique' => 'Branch already exists!',
];
$this->validate($request, [
'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
return $query->where('subscriber_id', $subscriber_id);
})
], $messages);
Branch::where('id', $id)->update([
'description' => $description,
'message' => $message,
]);
return redirect('branches')->with('success', 'Branch info successfully updated!');
}
Note: the url of the edit form is /branch/edit/{id} while the page I want to redirect after submission is /branches.
Is my validation wrong? Did I miss something?
Thanks! :)
According to the laravel docs you can redirect to a different route by using the Validator facade
public function update(Request $request, $id)
{
$description = $request->input('description');
$message = $request->input('message');
$subscriber_id = auth()->user()->subscriber_id;
$messages = [
'description.unique' => 'Branch already exists!',
];
$validator = Validator::make($request->all(), [
'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
return $query->where('subscriber_id', $subscriber_id);
})
],
$messages);
if ($validator->fails()) {
return redirect('/branches')
->withErrors($validator)
->withInput();
}
Branch::where('id', $id)->update([
'description' => $description,
'message' => $message,
]);
return redirect('branches')->with('success', 'Branch info successfully updated!');
}
Make sure you use the Validator facade at the beginning of your controller file use Validator;
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