I am trying to insert image in database using laravel 5.4. It works. But when I search that directory then it does not appear there. I also want to validate only images should be upload and size.
Thanks for advance.
My Controller function is here
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Hash;
use App\User;
class regController extends Controller
{
public function create(Request $request)
{
$this-> validate(request(),[
'name' => 'required',
'email'=> 'required',
'type' => 'required',
'image' => 'required',
'password' => 'required|confirmed|min:6',
]);
$request['password'] = bcrypt($request -> password);
$User = new User($request->input()) ;
if($file = $request->hasFile('image')) {
$file = $request->file('image') ;
$fileName = $file->getClientOriginalName() ;
return Storages::putFile('public/images',$request->file('image'));
$destinationPath = public_path().'images/' ;
$file->move($destinationPath,$fileName);
$User->image = $fileName ;
}
$user =
User::create(request(['name','email','type','image','password']));
return redirect('login');
}
try this :
// Validation
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,bmp,png|max:10240' // size in kelobytes this equals 10 mb
]);
$User = new User() ;
$User->password = bcrypt($request->password);
$User->name = $request->name;
$User->type = $request->type;
$User->email = $request->email;
$filename = $this->getFileName($request->image);
$request->image->move(base_path('public/images'), $filename);
$User->image = $fileName;
$$User->save();
return back()->with('success','Image Upload successful');
I just forgot to show you how to implement getFileName function to generate a unique filename sorry about that, in your controller you can define it as protected method like so:
protected function getFileName($file)
{
return str_random(32) . '.' . $file->extension();
}
I think you are tryin to do smth like this:
public function fileUpload(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$input['imagename'] = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $input['imagename']);
$this->postImage->add($input);
return back()->with('success','Image Upload successful');
}
Related
How to update image in this code?
this is the Web.php file
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\auth\DashboardController;
use App\Http\Controllers\auth\ServicesController;
use App\Http\Controllers\Auth\TournamentController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
//Admin Middleware
Route::prefix('admin')->middleware(['auth', 'isAdmin'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'dashboard']);
Route::get('/alltournaments', [TournamentController::class, 'createview']);
Route::get('/create', [TournamentController::class, 'create']);
Route::post('/save-tournament', [TournamentController::class, 'saveTournament']);
Route::get('/edit-tournament/{id}', [TournamentController::class, 'editTournament']);
Route::post('/update-tournament', [TournamentController::class, 'updateTournament']);
Route::get('delete-tournament/{id}', [TournamentController::class, 'deleteTournament']);
Route::get('/manage', [TournamentController::class, 'manage']);
});
//User Middleware
Route::middleware(['auth', 'isUser'])->group(function () {
});
//Public Routes
Route::get('/', [TournamentController::class, 'index']);
Route::get('/tournament/{id}', [TournamentController::class, 'singleTournament']);
And this is controller
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use App\Models\Tournament;
use Illuminate\Support\Facades\File;
class TournamentController extends Controller
{
public function index(){
$data = Tournament::latest()->get();
foreach($data as $d){
if($d->teamsize == 1){
$d->teamsize = "Solo";
}elseif($d->teamsize == 2){
$d->teamsize = "Duo";
}elseif($d->teamsize == 4){
$d->teamsize = "Squad";
}
}
return view('site.home', compact('data'));
}
public function createview(){
$data = Tournament::latest()->get();
foreach($data as $d){
if($d->teamsize == 1){
$d->teamsize = "Solo";
}elseif($d->teamsize == 2){
$d->teamsize = "Duo";
}elseif($d->teamsize == 4){
$d->teamsize = "Squad";
}
}
return view('auth.createmain',compact('data'));
}
//manage view
public function manage(){
$data = Tournament::latest()->get();
return view('auth.manage', compact('data'));
}
//create view
public function create(){
return view('auth.create');
}
//Create
public function saveTournament(Request $request ){
$request->validate([
'tournament_name'=> 'required',
'teamsize'=> 'required',
'check_in_period'=> 'required',
'formate'=> 'required',
'fee'=> 'required',
'prize_pool'=> 'required',
'overview'=> 'required',
]);
$tournament_name =$request->tournament_name;
$teamsize =$request->teamsize;
$check_in_period =$request->check_in_period ;
$formate =$request->formate;
$fee =$request->fee;
$prize_pool =$request->prize_pool;
$overview =$request->overview;
$tournament = new Tournament();
$tournament->title = $tournament_name;
$tournament->check_in_period = $check_in_period;
$tournament->entry_fee = $fee;
$tournament->formate = $formate;
$tournament->overview = $overview;
$tournament->teamsize = $teamsize;
$tournament->prize_pool = $prize_pool;
if($request->hasfile('thumnial'))
{
$file=$request->file('thumnial');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('images/thumnail/',$filename);
$tournament->thumnail=$filename;
}
if($request->hasfile('banner'))
{
$file=$request->file('banner');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('images/banner/',$filename);
$tournament->banner=$filename;
}
$tournament->save();
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Added');
}
//create END
public function editTournament($id){
$data = Tournament:: where('id', '=', $id)->first();
return view('auth.edit', compact('data'));
}
public function updateTournament(Request $request){
$request->validate([
'tournament_name'=> 'required',
'teamsize'=> 'required',
'check_in_period'=> 'required',
'formate'=> 'required',
'fee'=> 'required',
'prize_pool'=> 'required',
'overview'=> 'required',
]);
$id =$request->id;
$tournament_name =$request->tournament_name;
$teamsize =$request->teamsize;
$check_in_period =$request->check_in_period ;
$formate =$request->formate;
$fee =$request->fee;
$prize_pool =$request->prize_pool;
$overview =$request->overview;
Tournament::where('id' , '=', $id)->update([
'title'=> $tournament_name,
'teamsize'=>$teamsize,
'check_in_period'=> $check_in_period,
'formate'=>$formate,
'entry_fee'=>$fee,
'prize_pool'=>$prize_pool,
'overview'=>$overview,
]);
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Edited');
}
//Delete
public function deleteTournament($id){
Tournament::where('id' , '=', $id)->delete();
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Deleted');
}
//User View
public function singleTournament($id){
$data = Tournament:: where('id', '=', $id)->first();
if($data->teamsize == 1){
$data->teamsize = "Solo";
}elseif($data->teamsize == 2){
$data->teamsize = "Duo";
}elseif($data->teamsize == 4){
$data->teamsize = "Squad";
}
return view('site.tournament',compact('data'));
}
}
I need to update image
You can update the image by only inserting this small code:
if ($request->hasfile('banner')) {
$file = $request->file('banner');
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('images/banner'), $filename);
$banner = $filename;
}
Also, below i update your function:
public function updateTournament(Request $request)
{
$request->validate([
'tournament_name' => 'required',
'teamsize' => 'required',
'check_in_period' => 'required',
'formate' => 'required',
'fee' => 'required',
'prize_pool' => 'required',
'overview' => 'required',
]);
$id = $request->id;
$tournament_name = $request->tournament_name;
$teamsize = $request->teamsize;
$check_in_period = $request->check_in_period;
$formate = $request->formate;
$fee = $request->fee;
$prize_pool = $request->prize_pool;
$overview = $request->overview;
if ($request->hasfile('banner')) {
$file = $request->file('banner');
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('images/banner'), $filename);
$banner = $filename;
Tournament::where('id', $id)->update(['banner' => $banner]);
}
Tournament::where('id', $id)->update([
'title' => $tournament_name,
'teamsize' => $teamsize,
'check_in_period' => $check_in_period,
'formate' => $formate,
'entry_fee' => $fee,
'prize_pool' => $prize_pool,
'overview' => $overview,
]);
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Edited');
}
I want to upload image for my posts and have polymorphism relation one to one (because I have other tables and they need image too ) between posts and images
And when I want to send request and store the image in database , I get this error:
BadMethodCallException: Call to undefined method App\Models\Image::move()
I'm creating an API so :
My postman :
My relations :
Image model :
class Image extends Model
{
use HasFactory;
protected $fillable = [
'image'
];
public function imageable(){
return $this->morphTo();
}
}
Post model :
class Post extends Model
{
use HasFactory;
use \Conner\Tagging\Taggable;
protected $fillable = [
'user_id' ,
'category_id' ,
'title' ,
'body' ,
'study_time',
'likes',
'status',
'tags',
];
public function image(){
return $this->morphOne(Image::class , 'imageable');
}
}
And the PostController , store() method :
public function store(Request $request )
{
$data = $request->all();
$validator = Validator::make($data, [
'user_id'=>'required',
'category_id'=>'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time'=>'required',
'tags'=>'nullable|string',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'error']);
}
//separate tags
$tags = explode(",", $request->tags);
$image = new Image;
$getImage = $request->file('image');
$imageName = time().'.'.$getImage->extension();
$image->move(public_path('images'), $imageName);
$post = Post::create($data);
$post->image()->save($image);
//save tags
$post->tag($tags);
return response()->json([
"success" => true,
"message" => "successfull",
"data" => $post
]);
}
Where is my mistake?
After a month of this challenge, I was finally able to solve it :}
To make the code better and cleaner, I added another column to my image table : path
it's for saving path of image , and another column : image
and i added the path to my fillable in Image model and i edited the code to this :
public function store(Request $request )
{
$data = $request->all();
$validator = Validator::make($data, [
'user_id'=>'required',
'category_id'=>'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time'=>'required',
'tags'=>'nullable|string',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'error']);
}
//separate tags
$tags = explode(",", $request->tags);
$image = new Image;
$getImage = $request->image
$imageName = time().'.'.$getImage->extension();
$imagePath = public_path(). '/images/posts';
$image->path = $imagePath;
$image->image = $imageName;
$getImage->move($imagePath, $imageName);
$post = Post::create($data);
$post->image()->save($getImage);
$post->tag($tags);
return response()->json([
"success" => true,
"message" => "successfully",
"data" => $post
]);
}
I am trying to upload an image into the database. The image is not uploading properly, how can I fix it?
The image path is uploading into database like this: {"image":"phpV3IZnF.png"}
it should be like this: phpV3IZnF.png
Controller
public function servicesaction(Request $request)
{
$this->validate($request,[
'name' => 'required',
'description'=>'required',
'image' =>'required']);
$name=$request->get('name');
$description = $request->get('description');
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
Storage::disk('cms')->put($image->getFilename().'.'.$extension,
File::get($image));
$content = new Services;
$content->image = $image->getFilename().'.'.$extension;;
check = Services::where('id', $content->id)->select('image')-
>create(['service_name'=>$name,'description'=>
$description,'image'=>$content ])->get();
return back()->with('success', 'Success Successfully Inserted')-
>with('path', $check);
}
you can get file name like below
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
then save the name into database
Replace servicesaction function with below code
public function servicesaction(Request $request)
{
$this->validate($request,[
'name' => 'required',
'description'=>'required',
'image' =>'required']);
$name=$request->get('name');
$description = $request->get('description');
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
Storage::disk('cms')->put($image->getFilename().'.'.$extension,
File::get($image));
$content = new Services;
$content->image =$image->getClientOriginalName().'.'.$extension;;
check = Services::where('id', $content->id)->select('image')-
>create(['service_name'=>$name,'description'=>
$description,'image'=>$content ])->get();
return back()->with('success', 'Success Successfully Inserted')-
>with('path', $check);
}
change getFilename() to getClientOriginalName()
Like this
$extension = $image->getClientOriginalExtension()
$content->image = $image->getClientOriginalName().'.'.$extension;
Just Change 'image'=>$content to 'image'=>$content->image in the your create function
check = Services::where('id', $content->id)->select('image')
->create(['service_name'=>$name,'description'=> $description, 'image'=>$content->image ]) //use $content->image here
->get();
I want to save image name to database but it always save to C:\xampp\tmp\phpAB3A.tmp. btw im not using xampp, im using laragon.How to change the path? i want to save to storage/app/public
'name'=> 'required',
'email' => 'required',
//'logo' => 'required',
$imageName = time().'.'.request()->logo->getClientOriginalExtension();
request()->logo->move(storage_path('app/public'), $imageName);
Company::create($request->all());
return redirect()->route('company.dashboard')->with('Success');
In your Company::create you have to define the path... Something like:Company::create([
'path' => torage_path('app/public',$imageName),....]);
I'm using laravel 5.8 and this code worked for me.
In controller
<?php
public function store()
{
// I did like this, because storeLogo method is reusable
$data = request()->validate([ /* ... */ ]);
$company = Company::create($data);
$this->storeLogo($company);
// but you can do like this
$data = request()->validate([ /* ... */ ]);
if (request()->has('logo')) {
$data['logo'] = request()->logo->store('', 'public');
}
$company = Company::create($data);
}
private function storeLogo(Company $company)
{
if (request()->has('logo')) {
$company->update([
'logo' => request()->logo->store('', 'public'),
// logo file is stored at /storage/app/public/
]);
}
}
$input = $request->all();
$fileName = '';
if ($request->hasFile('logo')) {
$destinationPath = storage_path('app/public');
$file = $request->logo;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
}
$input['logo'] = $fileName;
Company::create($input);
I have an Image model it saves data through the controller but it doesn't display data, please what's the issue.
The Model
namespace App;
use App\Event\NotifyPhoto;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public $table = "images";
protected $guarded = [];
public $timestamps = false;
public function property_user()
{
return $this->belongsTo('App\PropertyUser');
}
public function facility(){
return $this->belongsTo('App\Facility');
}
}
The Image controller
namespace App\Http\Controllers;
use App\Http\Requests\ImageRequest;
use App\Property;
use App\PropertyUser;
use Illuminate\Http\Request;
use App\Facility;
use App\Image;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Carbon;
class ImageController extends Controller
{
public function create()
{
dd(Image::all());//This comes back empty
return view('settings.photos');
}
public function store(Request $request)
{
$property_users = PropertyUser::where('user_id', '=', Auth::user()- >id)->get();
foreach ($property_users as $property_user) {
$id = $property_user->property_id;
}
$rules = [
'file' => 'required',
'description' => 'required',
'tag' => 'required'
];
$request->file('file');
if (!empty($request->file('file'))) {
$file_count = count($request->file('file'));
} else $file_count = null;
foreach (range(0, $file_count) as $index) {
$rules['file.' . $index] = 'image|mimes:jpeg,gif,webp,bmp,png|max:2048';
}
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
} else {
$files = $request->file('file');
$description = $request->input('description');
$tag = $request->input('tag');
$i = 0;
foreach ($files as $file) {
$i++;
$file1 = $file->move(public_path() . '/upload_images/', $file->getClientOriginalName());
$url1 = $url = URL::to("/") . '/upload_images/' . $file->getClientOriginalName();
$image = Image::create([
'filename' => $url,
'description' => $description,
'facility_id' => 16, //$new_fac->id ?? $f->id,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
'tag' => $tag
]);
dd($image);//This displays the files saved and their ids in the table
]
}
return redirect('settings/photos');
}
}
}
Try adding this to your App/Image:
protected $fillable = [
'filename',
'description',
'facility_id',
'created_at',
'updated_at',
'tag',
];
https://laravel.com/docs/5.6/eloquent#mass-assignment
Also, can you confirm a new row is being added to the database?