Image is not shwing in the user profile in Laravel - php

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 }}"/>

Related

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'listeners')

I was trying out the temporary preview Urls in livewire to preview image before uploading them and I kept getting errors, despite following every step in the example on the livewire website. I have combed through the internet to find solutions to the problem and I have not been able to figure out where the error is. I will appreciate if someone can help me out with this. This was on my local machine and not a live environment.
<!--Multiple File Upload -->
<div class="w-full">
<div class="flex">
#if($photos)
Photo Preview:
<div class="flex bg-blue-200 p-4 rounded-lg">
#foreach($photos as $photo)
<img class="w-32 h-32 p-2 rounded-lg" src="{{ $photo->temporaryUrl() }}">
#endforeach
</div>
#endif
</div>
<div class="flex">
<div wire:loading wire:target="photos">Uploading...</div>
<form wire:submit.prevent="save">
<input type="file" wire:model="photos" multiple>
#error('photos.*') <span class="error">{{ $message }}</span> #enderror
<button type="submit" class="bg-blue-300 p-2 rounded-lg">Save Multi Photo</button>
</form>
</div>
</div>
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
class MultiUpload extends Component
{
use WithFileUploads;
public $photos = [];
public function save()
{
$this->validate([
'photos.*' => 'image|max:1024', // 1MB Max
]);
foreach ($this->photos as $photo) {
$photo->store('images');
}
}
public function render()
{
return view('livewire.multi-upload');
}
}

laravel 7 calling a method function for delete a file

i tried now long enough how i call the delete function from my mediacontroller in my media index.blade. I dont get it. So if someone of you give me a tipp please answer! I would really appreciate it!
Thats my media index.blade.php:
<div class="container">
<div class="row">
<div class="col-4">
<div class="card">
<div class="card-header">
<h3>Upload</h3>
</div>
<div class="card-body">
<form method="post" enctype="multipart/form-data" action="{{"upload"}}">
#csrf
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="media"
aria-describedby="media" name="file">
<label class="custom-file-label" for="media">Datei auswählen</label>
</div>
</div>
#error('file')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
<hr/>
<button class="btn btn-success">Hochladen</button>
</form>
</div>
</div>
</div>
<div class="col-8">
<div class="card">
<div class="card-header">
<h1>Media</h1>
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
</div>
<div class="card-body">
<form action="{{route('media.index')}}" method="GET" role="search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="q" value="{{request()->input("q")}}"
placeholder="Suche...">
<span class="input-group-btn">
<button type="submit" class="btn btn-light">
<span class="fa fa-search"></span>
</button>
</span>
</div>
</form>
<br/>
#if($medias->count() > 0 )
<table class="table table-bordered table-hover">
<thead>
<th>ID</th>
<th>Dateiname</th>
<th>Extension</th>
<th>Größe</th>
<th>Preview</th>
</thead>
<tbody>
#foreach($medias as $media)
<tr>
<td>{{$media->id}}</td>
<td>{{$media->name}}</td>
<td>{{$media->extension}}</td>
<td>{{$media->size}}</td>
<td><a href="{{route('media', $media->id)}}">
#if(in_array($media->extension, ["jpg", "jpeg", "bpm", "png", "gif"]))
<img src="{{route("media", $media->id)}}" width="150"/>
#else
#switch($media->extension)
#case("pdf")
<i class="fa fa-file-pdf"></i>
#break
#case("xsls")
<i class="fa fa-file-excel"></i>
#break
#case("doc")
<i class="fa fa-file-word"></i>
#break
#case("docx")
<i class="fa fa-file-word"></i>
#break
#case("svg")
<i class="fa fa-vector-square"></i>
#break
#endswitch
#endif
</a></td>
</td>
<td> <i class="fa fa-trash"></i>
</td>
</tr>
#endforeach
</tbody>
</table>
#else
<h4>Es wurden keine Daten gefunden</h4>
#endif
{{$medias->links()}}
</div>
</div>
</div>
</div>
</div>
now my web.php with the routes:
Route::resource("kitas", "KitaController");
Route::resource("users", "UserController");
Route::resource("posts", "PostController");
Route::post("/upload", "MediaController#upload")->name("upload");
Route::get("media", "MediaController#index")->name("media.index");
Route::get("media/{id}/delete", "MediaController#index")->name("media.delete");
Route::get("/media/{id}", "MediaController#download")->name("media");
Route::get("/media/{id}/preview", "MediaController#preview")->name("media.preview");
and now my MediaController:
class MediaController extends Controller
public function index() {
$q = request()->input("q");
if($q) {
$medias= Media::where('name','LIKE','%'.$q.'%')->orderByDesc('created_at')->paginate(10);
}else {
$medias = Media::orderByDesc('created_at')->paginate(10);
}
return view("media.index")->with(["medias" => $medias]);
}
public function upload( Request $request)
{
$request->validate([
"file" => "required"
]);
$name = $request->file("file")->getClientOriginalName();
$extension = $request->file("file")->getClientOriginalExtension();
$size = $request->file("file")->getSize();
$path = $request->file("file")->store("public/media");
Media::create([
"name" => $name,
"extension" => $extension,
"size" => $size,
"path" => $path
]);
return redirect()->route("media.index")->withStatus("Datei wurde erfolgreich hochgeladen!");
}
public function download($id)
{
$media = Media::find($id);
$file = storage_path(). "/app/". $media->path;
return response()->file($file);
}
public function preview($id)
{
$media = Media::whereIn('extension', ["jpg", "png", "gif", "bmp"])->where("id", "=", $id)->first();
$file = storage_path(). "/app/". $media->path;
$preview = Image::make($file)->resize(200, 200);
return $preview->response();
}
public function delete($id)
{
$media = Media::find($id);
$media -> delete();
}
I can click the delete buttons on the website, but nothing happens.
I cant find the solution. or work it out for myself. the sheer amount of different ways you can solve things with coding drives me nuts. I try to code now for like 9 months and i just get slowly forward, since Iam more used to have one solution to get to the goal not 500 differnt ones. Makes me a bit upset to get behind all the stuff.
Do you have also tipps how to learn to code from zero to hero?
thanks!
Pommesfee
SO, thats my delete route:
Route::get("media/{id}/delete", "MediaController#index")->name("media.delete");
and that would be the button to delete the image?
<form action="{{ route('media.delete', [$media->id]) }} method="DELETE">
#method('DELETE')
#csrf
</form>
I dont get behind about that and how to transfer it to my needs.
The default delete route generated by a resourceful route like
Route::resource("foo", "FooController");
will only accept a DELETE request.
Now, there isn't actually a DELETE method for a HTML Form so you will need to do what Laravel refers to as "Form Method Spoofing"
https://laravel.com/docs/7.x/routing#form-method-spoofing
<form action="/foo/bar" method="POST">
#method('DELETE')
#csrf
</form>
If you are looking for a good resource to learn Laravel (and other related frameworks), i would suggest Laracasts
Addendum
You are specifying a GET request which will not work. You should specify a DELETE request like so:
Route::delete("media/{id}/delete", "MediaController#index")->name("media.delete");
You also need to use the POST method on the form AND add the form model spoofing like so:
<form action="{{ route('media.delete', [$media->id]) }} method="POST">
#method('DELETE')
#csrf
</form>

Save Url of image to database and get image

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

Laravel Errors validation returning null

Yesterday I started with Laravel, currently busy with my first project, a simple news page.
Unfortunately, I've met some problems while validating my post request, I've tried to search on Google for my issue. And I tried to use those fixes, but strange enough I had no result.
The problem is:
When I post data the normal 'form page' will be shown without any errors. I'm aware that I have double error outputs, it's just for the test.
What do I want to reach?
I want that the validation error will be shown
routes.php
<?php
Route::group(['middleware' => ['web']], function() {
Route::get('/', function() {
return redirect()->route('home');
});
Route::get('/home', [
'as' => 'home',
'uses' => 'HomeController#home',
]);
Route::get('/add_article', [
'as' => 'add_article',
'uses' => 'HomeController#add_article',
]);
Route::post('/add_article', [
'as' => 'add_article.newarticle',
'uses' => 'HomeController#post_article',
]);
});
HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\News;
class HomeController extends Controller
{
public function home(News $news)
{
$articles = $news->orderBy('id','desc')->take(3)->get();
return view('home.home')->with('articles', $articles);
}
public function add_article()
{
return view('home.add_article');
}
public function post_article(Request $request)
{
$this->validate($request, [
'title' => 'required|max:64',
'content' => 'required|max:2048',
]);
// $newNews = new News;
// $newNews->title = $request->title;
// $newNews->content = $request->content;
// $newNews->save();
}
}
add_article.blade.php
#extends('templates.default')
#section('content')
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 offset-md-3 offset-lg-3 offset-xl-3">
<p class="lead">New news article</p>
<div class="card">
<div class="card-header">
<h5 class="mb-0"> </h5>
</div>
<div class="card-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ route('add_article.newarticle') }}">
<div class="form-group">
<label for="title" style="margin-bottom:0px;">
Title:
</label>
<input class="form-control" type="text" name="title" placeholder="Please enter your title!" id="title">
#if ($errors->has('title'))
{{ $errors->first('title') }}
#endif
</div>
<div class="form-group">
<label for="content" style="margin-bottom:0px;">
Content:
</label>
<textarea class="form-control" rows="3" name="content" placeholder="Please enter your message!" id="content" style="resize:none;"></textarea>
#if ($errors->has('content'))
{{ $errors->first('content') }}
#endif
</div>
<div class="form-group text-right">
<button class="btn btn-primary" type="submit">
Create news
</button>
</div>
{{ csrf_field() }}
</form>
</div>
</div>
</div>
</div>
#endsection
I hope someone can help me to resolve this issue!
use App\Http\Requests;
Remove This from HomeController.php and try.
Your validation is passing but you are not doing anything after so it's not going to show anything unless you tell it to.
Also make sure you use $request->all() instead of $request in the validator as the first one will return the actual input values that were submitted.
use Validator;
public function post_article(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|max:64',
'content' => 'required|max:2048',
]);
if ($validator->fails()) {
return redirect('home')
->withErrors($validator)
->withInput();
}
// $newNews = new News;
// $newNews->title = $request->title;
// $newNews->content = $request->content;
// $newNews->save();
return redirect()->route('home')->with('message', 'Article created.');
}
}
Then in your view add the following at the top:
#if(Session::has('message'))
<div class="alert alert-success">
×
{{ Session::get('message') }}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Based on those validation rules you will only see errors when the title is empty or longer than 64 characters, or the content is empty or longer than 2048 characters. Make sure the data you are testing with is long enough to trigger any errors.
For data that passes validation the code currently does not save (commented out), nor does it return a new location or view so it will show a blank page. You should probably save the data and redirect to the index or a show page with a success message.

How do i save the file name/image through my database?

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

Categories