Im currently doing the file upload. I searched through the internet regarding the file upload. The website that I saw is only saving through the images folder, i tried to put the Administrator::create(['image' => $request->image]);
It saved to the database but its not the name of the image that i upload.. The name of the image after i-upload C:\xampp\tmp\php306A.tmp
My Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Administrator;
class ImageController extends Controller
{
/**
* Create view file
*
* #return void
*/
public function imageUpload()
{
return view('image-upload');
}
/**
* Manage Post Request
*
* #return void
*/
public function imageUploadPost(Request $request)
{
$file = $request->file('image');
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);
// Administrator::create($request->all());
Administrator::create([
'image' => $request->image
]);
return back()
->with('success','Image Uploaded successfully.')
->with('path',$imageName);
}
}
?>
My View
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.3 Image Upload with Validation example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading"><h2>Laravel 5.3 Image Upload with Validation example</h2></div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<img src="/images/{{ Session::get('path') }}">
#endif
<form action="{{ url('image-upload') }}" enctype="multipart/form-data" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-md-12">
<input type="file" name="image" />
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
My Routes
Route::get('image-upload','ImageController#imageUpload');
Route::post('image-upload','ImageController#imageUploadPost');
My model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Administrator extends Model
{
protected $table = 'accounts';
protected $fillable = array(
'first_name',
'middle_name',
'last_name',
'email',
'image',
''
);
}
To get the uploaded image, you could change these lines:
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);
to
$imageName = "";
if($request->hasFile('images')) {
$image = $request->file('images');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $imageName);
}
And your create part:
Administrator::create([
'image' => $imageName
]);
view part
{!! Form::open(array('url'=>'insertfile','method'=>'POST' ,'class'=>'form-horizontal','files'=>true)) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Upload:</label>
<div class="col-sm-4">
<input type="file" name="filenam" class="filename">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
{!! Form::close() !!}
controller
public function insertFile(){
$file= Input::file('filenam');
$rules = array('file' => 'required|max:10000|mimes:jpeg,png,jpg,gif,svg,csv,xls,xlsx,doc,docx,pdf');
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'up_file';
$filename = $file->getClientOriginalName();
$data=array(
'file_name' => $filename,
);
var_dump($data);
yourmodelname::insert($data);
$upload_success = $file->move($destinationPath, $filename);
}
}
in route:
Route::get('/uploadfile','UploadController#getView');
Route::post('/insertfile','UploadController#insertFile');
file will be upload in yourproject/public/up_file directory
Related
Here I have two tables in my database named user and products
here is user.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
}
using this table I can register and login by email address. after login it takes me to a page called index.blade.php where I have a button called add data after clicking it, it takes me to my create.blade.php page where I can register some data for the products table. after registered data, those data show me in index.blade.php. That's nice again I can add data and it shows in the index. there is no problem. But the problem is when I login from the index and registered again with a new email address and login with the new email address it's showing me old data I have added with my previous email. but I don't want to see old data after login with new email address.
here is my product.php table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->timestamps();
});
}
here is my ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProductController extends Controller
{
public function index()
{
if(Auth::check()){
$products = Product::latest()->paginate(1);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
}
public function create()
{
return view('products.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:640dp*480dp',
'logo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:512*512',
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}
Product::create($input);
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
public function show(Product $product)
{
return view('products.show',compact('product'));
}
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}else{
unset($input['logo']);
}
$product->update($input);
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
function indextwo(){
//return DB::select("select * from products");
//DB::table('products')->orderBy('id','desc')->first();
return Product::orderBy('id', 'DESC')->first();
}
}
here is Product.php as model
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo'
];
}
this is index.blade.php
#extends('products.layout')
#section('content')
<div class="row">
<div class="pull-right">
<!-- Authentication -->
<form method="POST" action="{{ route('logout') }}" style="margin: 20px">
#csrf
<x-jet-dropdown-link href="{{ route('logout') }}"
onclick="event.preventDefault();
this.closest('form').submit();">
{{ __('Log Out') }}
</x-jet-dropdown-link>
</form>
</div>
{{-- --}}
<div></div>
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Click Button</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('products.create') }}"> For New Data</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>App Name</th>
<th>App Logo</th>
<th>Splash Image</th>
<th>Description</th>
<th>Color</th>
<th width="280px">Action</th>
</tr>
#foreach ($products as $product)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $product->name }}</td>
<td><img src="/logo/{{ $product->logo }}" width="100px"></td>
<td><img src="/image/{{ $product->image }}" width="100px"></td>
<td>{{ $product->detail }}</td>
<td>{{ $product->color }}</td>
<td>
<form action="{{ route('products.destroy',$product->id)}}" method="POST">
<a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>
<a class="btn btn-info" href="products_link">Get Json</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $products->links() !!}
#endsection
and this is create.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
{{-- <title>Document</title> --}}
<title>Bootstrap Colorpicker Example - nicesnippets.com</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-colorpicker/2.5.1/css/bootstrap-colorpicker.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-colorpicker/2.5.1/js/bootstrap-colorpicker.min.js"></script>
</head>
<body>
#extends('products.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Add New Data</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('products.index') }}"> Back</a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('products.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-4">
<div class="form-group">
<strong>Detail:</strong>
<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
</div>
</div>
<div class="container">
<strong>Color picker</strong>
<div id="cp2" class="input-group colorpicker colorpicker-component">
<input type="text" value="#00AABB" class="form-control" name="color" placeholder="Color" />
<span class="input-group-addon"><i></i></span>
</div>
</div>
<div class="col-xs-4">
<div class="form-group">
<strong>Logo:</strong>
<input type="file" name="logo" class="form-control" placeholder="logo">
</div>
</div>
<div class="col-xs-4">
<div class="form-group">
<strong>Image:</strong>
<input type="file" name="image" class="form-control" placeholder="image">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<script type="text/javascript">
$('.colorpicker').colorpicker({});
</script>
#endsection
</body>
</html>
I have done this by ```` Auth::id()
After setting up my profile page my uploaded images initially produced an image on my local host. However lately it shows up as an icon instead https://i.stack.imgur.com/pp0Yt.png
I should note I am using php 7.3.19
profiles/index.blade.php
<div class="container">
<div class="row">
<div class="col-3 p-5">
<img src="{{ $user->profile->profileImage() }}" class="rounded-circle w-100">
</div>
<div class="col-9 pt-5">
<div class="d-flex justify-content-between align-items-baseline">
<div class="d-flex align-items-center pb-3">
<div class="h4">{{ $user->username }}</div>
<follow-button user-id="{{ $user->id }}" follows="{{ $follows }}"></follow-button>
</div>
#can('update', $user->profile)
Add New Post
#endcan
</div>
#can('update', $user->profile)
Edit Profile
#endcan
<div class="d-flex">
<div class="pr-5"><strong>{{ $postCount }}</strong> posts</div>
<div class="pr-5"><strong>{{ $followersCount }}</strong> followers</div>
<div class="pr-5"><strong>{{ $followingCount }}</strong> following</div>
</div>
<div class="pt-4 font-weight-bold">{{ $user->profile->title }}</div>
<div>{{ $user->profile->description }}</div>
<div>{{ $user->profile->url }}</div>
</div>
</div>
<div class="row pt-5">
#foreach($user->posts as $post)
<div class="col-4 pb-4">
<a href="/p/{{ $post->id }}">
<img src="/storage/{{ $post->image }}" class="w-100">
</a>
</div>
#endforeach
</div>
</div>
#endsection
Is there an issue in the way I am picking it up from the storage?
I used 'php artisan storage:link'
create.blade.php
<div class="container">
<form action="/p" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-8 offset-2">
<div class="row">
<h1>Add New Image</h1>
</div>
<div class="form-group row">
<label for="caption" class="col-md-4 col-form-label">Post Caption</label>
<input id="caption"
type="text"
class="form-control{{ $errors->has('caption') ? ' is-invalid' : '' }}"
name="caption"
value="{{ old('caption') }}"
autocomplete="caption" autofocus>
#if ($errors->has('caption'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('caption') }}</strong>
</span>
#endif
</div>
<div class="row">
<label for="image" class="col-md-4 col-form-label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#if ($errors->has('image'))
<strong>{{ $errors->first('image') }}</strong>
#endif
</div>
<div class="row pt-4">
<button class="btn btn-primary">Add New Post</button>
</div>
</div>
</div>
</form>
</div>
#endsection
PostsController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$users = auth()->user()->following()->pluck('profiles.user_id');
$posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5);
return view('posts.index', compact('posts'));
}
public function create()
{
return view('posts.create');
}
public function store()
{
$data = request()->validate([
'caption' => 'required',
'image' => ['required', 'image'],
]);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
auth()->user()->posts()->create([
'caption' => $data['caption'],
'image' => $imagePath,
]);
return redirect('/profile/' . auth()->user()->id);
}
public function show(\App\Post $post)
{
return view('posts.show', compact('post'));
}
}
ProfilesController.php
<?php
namespace App\Http\Controllers;
use App\Profile;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Cache;
class ProfilesController extends Controller
{
public function index(User $user)
{
$follows = (auth()->user()) ? auth()->user()->following->contains($user->id) : false;
$postCount = Cache::remember(
'count.posts.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->posts->count();
});
$followersCount = Cache::remember(
'count.followers.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->profile->followers->count();
});
$followingCount = Cache::remember(
'count.following.' . $user->id,
now()->addSeconds(30),
function () use ($user) {
return $user->following->count();
});
return view('profiles.index', compact('user', 'follows', 'postCount', 'followersCount', 'followingCount'));
}
//($user = (User::findOrFail($user));)
//('user' => $user)
//
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profiles.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'url' => 'url',
'image' => '',
]);
if (request('image')) {
$imagePath = request('image')->store('profile', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1000, 1000);
$image->save();
$imageArray = ['image' => $imagePath];
}
auth()->user()->profile->update(array_merge(
$data,
$imageArray ?? []
));
return redirect("/profile/{$user->id}");
}
public function show($user_id)
{
$user = User::find(1);
$user_profile = Profile::info($user_id)->first();
return view('profiles.show', compact('profile', 'user'));
}
public function profile()
{
return $this->hasOne('Profile');
}
}
Use asset helper function to get the uploaded image URL.
<img src="{{ asset('storage/' . $post->image) }}" class="w-100">
OR
<img src="{{ asset(Storage::url($post->image)) }}" class="w-100">
I am having a little problem here. I am trying to put an image in my User Profile. The image is saved in the database and no errors are shown up, but I never see the default image that I gave to it. It says that it's there but The place for the pic stays empty.
This is what I've got for now:
UserController.php
<?php
namespace app\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
// namespace App\Http\Controllers\Controller;
// use App\Http\Requests\Request;
// use Illuminate\Http\Request;
class UserController extends Controller
{
public function profile()
{
$user = Auth::user();
return view('profile',compact('user',$user));
}
public function update_avatar(Request $request){
$request->validate([
'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user = Auth::user();
$avatarName = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
$request->avatar->storeAs('avatars',$avatarName);
$user->avatar = $avatarName;
$user->save();
return back()
->with('success','You have successfully upload image.');
}
/** Return view to upload file */
public function uploadFile(){
return view('uploadfile');
}
/** Example of File Upload */
public function uploadFilePost(Request $request){
$request->validate([
'fileToUpload' => 'required|file|max:1024',
]);
$request->fileToUpload->store('logos');
return back()
->with('success','You have successfully upload image.');
}
}
profile.blade.pbp
<hidden='Illuminate\Support\Facades\Auth'>
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
<div class="row justify-content-center">
<div class="profile-header-container">
<div class="profile-header-img">
<img class="rounded-circle" width="150" height="150" src="/storage/avatars/{{ $user->avatar }}" />
<!-- badge -->
<div class="rank-label-container">
<span class="label label-default rank-label">{{$user->name}}</span>
</div>
</div>
</div>
</div>
<div class="row justify-content-center">
<form action="/profile" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input type="file" class="form-control-file" name="avatar" id="avatarFile" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">Please upload a valid image file. Size of image should not be more than 2MB.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
#endsection
filesystems.php
'default' => env('FILESYSTEM_DRIVER', 'public'),
How can I make the default avatar visible?
Also, do you have any suggestions on how to put a watermark on the photos that will appear each time someone uploads photos?
Thanks in advance!
You can try this. First execute this command
php artisan storage:link
Then
<img class="rounded-circle" width="150" height="150" src="{{url('')}}/storage/avatars/{{ $user->avatar }}"/>
hello i just get an error in my blade it call
ErrorException (E_ERROR) Property [image_thumb_url] does not exist on
this collection instance. (View:
C:\xampp\htdocs\Madinatul-Quran\resources\views\backend\iklan\index.blade.php)
Previous exceptions Property [image_thumb_url] does not exist on this
collection instance. (0)
it start when i add modal in my index.blade does the controller caused that error?
here is my index.blade.php
<div id="modal_form_vertical" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{ route('iklan.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="modal-body">
<div class="form-group">
<div class="form-group col-sm-12 {{ $errors->has('image') ? 'has-error' : '' }}">
<div><label>Cover Iklan</label></div>
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 100px;">
<img src="{{ ($ads->image_thumb_url) ? $ads->image_thumb_url : 'http://placehold.it/200x150&text=Landscape' }}" alt="...">
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 100px;"></div>
<div>
<span class="btn btn-default btn-file"><span class="fileinput-new">Pilih Gambar</span><span class="fileinput-exists">Ganti</span><input type="file" name='image'></span>
Hapus
</div>
</div>
#if($errors->has('image'))
<span class="help-block">{{ $errors->first('image') }}</span>
#endif
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
and this is my controller
public function index()
{
$ads = Ads::latest()->get();
return view("backend.iklan.index", compact('ads'));
}
public function store(Request $request)
{
$this->validate($request, [
'image' => 'mimes:jpeg,png,jpg,svg,bmp'
]);
$ads = new Ads;
$ads->author_id = Auth::user()->id;
if ($request->hasFile('image'))
{
$file = $request->file('image');
$image = $file->getClientOriginalName();
$destination = public_path() . '/imgiklan/';
$successUploaded = $request->file('image')->move($destination, $file->getClientOriginalName());
if($successUploaded)
{
$extension = $file->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $image);
Image::make($destination . '/' . $image)
->resize(250, 170)
->save($destination . '/' . $thumbnail);
}
$ads->image = $image;
} else {
$ads->image = 'logo.jpg';
}
$ads->save();
return redirect()->route('iklan.index')->with('message', 'Iklan berhasil dibuat');
}
Ads is plural, you're getting multiple ads sorted descending by created_at (because you're using latest()). In your view you're accessing an attribute of a single ad. You should therefore use this in your controller index route:
$ads = Ads::latest()->first();
Then $ads will be filled with the latest result in your database instead of a collection of ads.
Hi I am New to Laravel I have done Upload a Image to path
img/banner/{{image upload here}}
My doubt is here is to save the image path in database with which
user uploaded
And while retrieving data how to give my URL path here.
I have created a database name uploads
id user_id group_id filename extension filesize location created_at updated_at
Blade File
<div class="panel panel-primary">
<div class="panel-heading"><h2>Slide Image Upload</h2></div>
<div class="panel-body">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<img src="/img/banner/{{ Session::get('image') }}">
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('image.upload.post') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6">
<input type="file" name="image" class="form-control">
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</div>
</form>
</div>
</div>
Controller:
public function imageUploadPost()
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->image->getClientOriginalExtension();
request()->image->move(public_path('img/banner'), $imageName);
return back()
->with('success','You have successfully upload image.')
->with('image',$imageName);
}
Routes:
Route::post('/imageupload', 'Admin\ImageController#imageUploadPost')->name('image.upload.post');
Any Help will be appreciated.
I am expecting that you have included namespace, if not
use DB;
$full_path = public_path('img/banner');
$ext = request()->image->getClientOriginalExtension();
$size = request()->image->getSize();
DB::table('uploads')->insert(
['group_id' => '1', user_id' => '1', 'filename' => $imageName,'filesize'=>$size ,'extension'=> $ext,'location' => $full_path,'created_at'=> date('Y-m-d H:m:s')]
);
You can get by this your database values, $imagename is the name you used to upload the image, not sure about your group_id so set to 1.
latest Edit
this is how you can get imageName:
$imageName = time().'.'.request()->image->getClientOriginalExtension();
froom your code only