I'm having a problem to get images uploaded. I have a default image to all the users. And when i choose other image to change the default one, it doesn't work. Somehow the $request is not being recognized.
The code of UserController:
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use Image;
public function updateAvatar(Request $request){
$user = User::find(Auth::user()->id);
if ($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename=time() . '.' . $avatar->getClientOriginalExtension();
if($user->avatar!='default.jgp'){
$file = 'uploads/avatars/' . $user->avatar;
if(File::exists($file)){
unlink($file);
}
}
Image::make($avatar)->save(public_path('/uploads/avatars/' . $filename));
$user= Auth::user();
$user->avatar=$filename;
$user->save();
}
return view('pages.AfterLogin.Entidade.users.profile')->withUser(Auth::user());
}
use dd($request); and show the screenshot and show the form as well.
I assume your method is correct. Try this:
use App\User;
use Illuminate\Http\Request;
use Auth;
use Image;
public function updateAvatar(Request $request){
$user = User::find(Auth::user()->id);
if ($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename=time() . '.' . $avatar->getClientOriginalExtension();
if($user->avatar!='default.jpg'){
$file = 'uploads/avatars/' . $user->avatar;
if(File::exists($file)){
unlink($file);
}
}
Image::make($avatar)->save(public_path('/uploads/avatars/' . $filename));
$user= Auth::user();
$user->avatar=$filename;
$user->save();
}
return view('pages.AfterLogin.Entidade.users.profile')->withUser(Auth::user());
}
I think you should try this::
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use Image;
use Illuminate\Support\Facades\Input;
public function updateAvatar(Request $request){
$user = User::find(Auth::user()->id);
if ($request->hasFile('avatar')){
$avatar = Input::file('avatar');
$filename=time() . '.' . $avatar->getClientOriginalExtension();
if($user->avatar!='default.jgp'){
$file = 'uploads/avatars/' . $user->avatar;
if(File::exists($file)){
unlink($file);
}
}
Image::make($avatar)->save(public_path('/uploads/avatars/' . $filename));
$user= Auth::user();
$user->avatar=$filename;
$user->save();
}
return view('pages.AfterLogin.Entidade.users.profile')->withUser(Auth::user());
}
Hope this work for you!
Related
I am trying to store an image in my images table that is related to the articles table
When I do this the following error appears:
Indirect modification of overloaded property App\Article::$thumbnail has no effect.
My Article Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $fillable = [
'title', 'exerpt', 'body'
];
public function author()
{
return $this->belongsTo(User::class, 'user_id');
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function thumbnail()
{
return $this->hasOne(Image::class);
}
}
My Image Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function article()
{
return $this->belongsTo(Article::class);
}
}
And the store method in my ArticleController:
public function store(Request $request)
{
$article = new Article($this->validateArticle($request));
//hardcoded for now
$article->user_id = 1;
$thumbnail = '';
$destinationPath = storage_path('app/public/thumbnails');
$file = $request->thumbnail;
$fileName = $file->clientExtension();
$file->move($destinationPath, $fileName);
$article->thumbnail->title = $file;
$article->save();
$article->tags()->attach(request('tags'));
return redirect(route('articles'));
}
Related to your Laravel version, this may works for you:
$article = new Article( $this->validateArticle( $request ) );
$article->user_id = 1;
$article->save();
$article->tags()->attach( request( 'tags' ) );
if( $request->hasFile( 'thumbnail' ) ) {
$destinationPath = storage_path( 'app/public/thumbnails' );
$file = $request->thumbnail;
$fileName = time() . '.'.$file->clientExtension();
$file->move( $destinationPath, $fileName );
$image = new Image;
$image->title = $fileName;
$image->article_id = $article->id;
$image->save();
}
public function store(Request $request){
$product = new product;
if($request->hasfile('image'))
{
$file = $request->file('image');
$exten = $file->getClientOriginalExtension();
$filename = time().".".$exten;
$file->move('uploads/product',$filename);
$product->image = $filename;
}
$product->save();
So, what i`m trying to do here is to save an image to an specific user that is logged in. and it gives me this error
<?php
namespace App\Http\Controllers\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Models\ProfileEmployee;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
class ImageUploadController extends Controller
{
public function index()
{
$profilasdeimage = ProfilasdeEmployee::where('uid', Auth::user()->id)->first();
return vieasdw('editareemasdployee', compact('profileiasdmage'));
}
public function store(Requasdest $request)
{
$emplasdoyee = ProfileEasdmployee::where('uiasdd', Autasdh::user()->id);
if ($request->hasfile('imasdage')){
$file = $request->file('image');
$exteasdnsion = $file->getClientOriginalExtension();
$fileasdname = md5(time()).'.'.$extension;
$fiasdle->move('public/imaginasdeprofil',$filename);
$empasdloyee->imagasde=$filename;
} else {
return $request;
$emplasdoyee->imasdage='';
}
$emplasdoyee->save(); --->> this is the problem
return view('imageuplasdoad')->with('profasdileimage',$emplasdoyee);
}
}
i want to use this database table to fill the 'image' using the id provided from table users as uid in this table
protected $filasdlable = [
'iasdd', 'uiasdd', 'fasdirst_nasdame', 'lasdast_nasdame','phasdone', 'casdv', 'imasdage', 'addasdress', 'ciasdty',
];
Add first() to your query or use find:
$employee = ProfileEmployee::where('uid', Auth::user()->id)->first();
I'm trying to use Image Intervention with laravel to resize images.
my code :
<?php
namespace App\Http\Controllers;
use App\Ad;
use App\Categorie;
use App\Http\Requests\AdsRequest;
use App\Mail\RejectedAd;
use App\Mail\ValidatedAd;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
class AdController extends Controller
{
/**
* AdController constructor.
*/
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
/**
* Store a newly created resource in storage.
*
* #param AdsRequest $request
* #return \Illuminate\Http\Response
*/
public function store(AdsRequest $request)
{
$validated = $request->validated();
$idAuthor = Auth::user()->id;
if (Auth::user()->activite !== 'particulier') {
$pro_ad = true;
} else {
$pro_ad = false;
}
$ad = new Ad();
$ad->title = $validated['title'];
$ad->content = $validated['content'];
$ad->price = $validated['price'];
$ad->zip = $validated['zip'];
$ad->city = $validated['city'];
$ad->categorie_id = $validated['categorie'];
$ad->user_id = $idAuthor;
$ad->publication_date = Carbon::now('Europe/Paris')->addDay(2);
if (isset($validated['descr']) && $validated['descr'] !== null) {
$ad->subcategory = $validated['descr'];
}
$ad->pro = $pro_ad;
$ad->save();
if (isset($validated['tag']) && $validated['tag'] !== null) {
$ad->Tag()->attach($validated['tag']);
}
$ad->save();
if ($request->hasFile('file')) {
Storage::disk('public')->makeDirectory("ad-$ad->id");
foreach ($request->file('file') as $image) {
if ($image) {
// Get filename with the extension
$filenameWithExt = $image->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $image->getClientOriginalExtension();
// Filename to store
$filenameToStore = $filename . '_' . time() . '.' . $extension;
// Upload image
$image->storeAs("/public/ad-$ad->id", $filenameToStore);
print_r('resize');
$img = Image::make(storage_path('app/public') . "/ad-$ad->id/" . $filenameToStore)->resize(400, 150, function ($constraint) {
$constraint->aspectRatio();
});
$img->save(storage_path('app/public') . "/ad-$ad->id/" . $filenameToStore);
print_r('resize fin');
$ad->File()->create(['path' => $filenameToStore]);
}
}
}
$ad->save();
return redirect(route('annonces.show', ['id' => $ad->id]));
}
}
but only the first print_r is displayed the rest is as not run.
Thank you in advance for your answers.
Nicolas
I am trying to populate the image_tag intermediate table with the ids of the image and the tag, however, I keep getting this error which from what I understand, says the the table name is incorrect even though it is not. It has columns image_id and tag_id which take unsigned integers.
"SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name 'image_tag ' (SQL: insert into image_tag (image_id, tag_id) values (17, 12))"
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();
$image->tags()->attach($tag);
return redirect()->route('home');
}
Image model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function tags(){
return $this->belongsToMany('App\Tag', 'image_tag ','image_id','tag_id');
}
}
Tag model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
public function images(){
return $this->belongsToMany('App\Image', 'image_tag','tag_id','image_id');
}
}
There is a space in 'image_tag ' that you wrote :|
return $this->belongsToMany('App\Tag', 'image_tag ','image_id','tag_id');
Clear your config cache and re-run the migrations.
How to store an avatar correctly
(in developer mode) The way I have my Controller now
it stores the new image path to the database but doesn't upload it to the 'uploads/avatars' folder.
Also when I try to just edit the profile without uploading a new avatar, it throws an ErrorException undefined variable:avatar,
and the version i have on my hosting server also throws the Errorexception if not uploading but only editing the profile,
And if I try to upload a new avatar it tells me
NotWritableException
Can't write image data to path (/home/vlindr.com/vlindr/public/uploads/avatars/1504691841.jpg)
Anybody knows how to go about fixing this?
My Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use Session;
use Image;
use Illuminate\Support\Facades\File;
use App\User;
use DB;
use Illuminate\Support\Facades\Storage;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
//
public function index(){
return view('profiles.profile', array('user' => Auth::user()) );
}
public function edit()
{
return view('profiles.edit')->with('info', Auth::user()->profile);
}
public function update(Request $request)
{
$this->validate($request, [
'location' => 'required',
'about' => 'required|max:355',
'passion' => 'required|max:355'
]);
Auth::user()->profile()->update([
'location' => $request->location,
'about' => $request->about,
'passion' => $request->passion
]);
$user = User::find(Auth::user()->id);
// Handle the user upload of avatar
if ($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
}
// Delete current image before uploading new image
if ($user->avatar !== 'man.png' && $user->avatar !== 'woman.png')
{
$file = public_path('/uploads/avatars/' . $user->avatar);
if (File::exists($file)) {
unlink($file);
}
}
Image::make($avatar->getRealPath())->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
return back()->with('msg', 'Profiel is bijgewerkt');
}
}