Laravel Image Intervention bug - php

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

Related

Laravel: save image in database

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();

How to fix this Uncaught UnexpectedValueException: Invalid route action

I'm trying to convert a closure-based routes to use a single action controller
So on my fuzzy.php inside routes folder i did this
write the codes
Route::get('theme/{file?}', 'FuzzyController')->name('fuzzy-theme.get');
and on my FuzzyController.php inside Core\Controllers\Assets
<?php
//namespace App\Http\Controllers;
namespace Core\Controllers\Assets;
// use App\User;
use App\Http\Controllers\Controller;
class FuzzyController extends Controller
{
/**
* Show the profile for the given user.
*
* #param int $id
* #return View
*/
public function __invoke(Request $request, $file = null)
{
$path = base_path(config('path.themes', 'themes').'/'.settings('active_theme', 'default'))."/$file";
$fileArray = explode('/', $file);
$lastFile = end($fileArray);
$extension = explode(".", $lastFile);
$fileExtension = end($extension);
$isCss = 'css' === $fileExtension ? true : false;
if (! in_array($fileExtension, config('downloadables', []))) {
return abort(403);
}
if (\File::exists($path)) {
$headers = [
'Cache-Control' => 'public',
'Content-Type' => 'text/css'
];
return response()->file($path, $isCss ? $headers : []);
}
return abort(404);
// return view('user.profile', ['user' => User::findOrFail($id)]);
}
}
can some explain why do i get an invalid route action thanks :D
The issue is because you haven't used namespace in your route definition. Change your route definition to:
Route::get('theme/{file?}', 'Core\Controllers\Assets\FuzzyController')->name('fuzzy-theme.get');
Hope this helps.

Posting value to database laravel

I'm trying to add a description to my thumbnail but it won't update in my database.
Can you guys see why?
The only thumb_description won't update.
Fillables are filled. When i did $content->save() it will return true.
Controller:
public function detail(Request $request, $id)
{
$content = Content_blocks::find($id);
if ($request->isMethod('post')) {
if ($request->hasFile('image')) {
$folder = 'uploads';
$name = $request->image->getClientOriginalName();
$store = $request->image->store($folder, 'public');
$file = pathinfo(Storage::url($store));
$thumb_description = $request->input('thumb_description');
$thumbnail = new Thumbnail();
$thumbnail->name = $file['filename'];
$thumbnail->extenstion = $file['extension'];
$thumbnail->path = $folder;
$thumbnail->thumb_description = $thumb_description;
$thumbnail->save();
$content->thumbnail_id = $thumbnail->id;
}
$content->title = $request->input('title');
$content->description = $request->input('description');
$content->link = $request->input('link');
$content->linkname = $request->input('linkname');
$content->order = $request->input('order');
$content->contentcategory_id = $request->input('categorie');
$content->thumbnail->thumb_description = $request->input('thumb_description');
if ($request->input('ontkoppel') === 'deletion') {
Thumbnail::find($content->thumbnail_id)->delete();
}
// dd($content->thumbnail->thumb_description);
$content->save();
return redirect('admin/content/webcategorie/homepage/contentblocks/' . $content->content_id);
}
Model
<?php
namespace App\Models;
use Illuminate\Support\Facades\Storage;
class Thumbnail extends Model
{
protected $fillable = [
"thumb_description",
"name",
"path",
"extenstion"
];
protected $table = 'thumbnail';
public function content()
{
return $this->belongsTo(Content::class);
}
public static function getFile($id)
{
$thumbnail = self::find($id);
if ($thumbnail === null) {
return null;
}
$url = sprintf('%s/%s.%s', $thumbnail->path, $thumbnail->name, $thumbnail->extenstion);
return Storage::disk('public')->url($url);
}
public static function getDescription($id)
{
$thumbnail = self::find($id);
if ($thumbnail === null) {
return null;
}
$description = $thumbnail->thumb_description;
return $description;
}
}
Migration
*/
public function up()
{
Schema::create('thumbnail', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->string('path', 150);
$table->string('extenstion', 10);
$table->text('thumb_description');
$table->timestamps();
});
}
Post in chrome dev tools
------WebKitFormBoundaryfun4SMk5TA604OZE
Content-Disposition: form-data; name="thumb_description"
bruyanga
$content->save(); will only save the attributes on $content and not its relationships.
Try $content->push(); instead which should cascade through the loaded relationships and save all related models as well.
https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Model.html#method_push

Request not recognized upload image

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!

Proper registering a Service Provider in Laravel 4.1 using $this->app->share()

I've written this image upload service but the problem is that I keep getting the following error.
I've tried a number of suggestions but I don't seem to get over it.
error type ReflectionException, message Class upload.image does not exist","file":"C:\xampp\htdocs\tippy\vendor\laravel\framework\src\Illuminate\Container\Container.php", line 501
ImageUploadService.php
namespace Tippy\Services\Upload;
use Intervention\Image\Image;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class ImageUploadService
{
protected $directory = 'assets/img/uploads/temp';
protected $extension = 'jpg';
protected $size = 160;
protected $quality = 65;
protected $filesystem;
public function __construct(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
public function enableCORS($origin)
{
$allowHeaders = [
'Origin',
'X-Requested-With',
'Content-Range',
'Content-Disposition',
'Content-Type'
];
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: ' . implode(', ', $allowHeaders));
}
protected function getFullPath($path)
{
return public_path() . '/' . $path;
}
protected function makeFileName()
{
return Sha1(time() . time()) . '.{$this->extension}';
}
protected function getFile($path)
{
$this->filesytem->get($path);
}
protected function getFileSize($path)
{
return $this->filesytem->size($path);
}
protected function getDataUrl($mime, $path)
{
$base = base64_encode($this->getFile($path));
return 'data:' . $mime . ';base64,' $base;
}
protected function getJsonBody($filename, $mime, $path)
{
return [
'images' => [
'filename' => $filename,
'mime' => $mime,
'size' => $this->getFileSize($path),
'dataURL' => $this->getDataUrl($mime, $path)
]
];
}
public function handle(UploadedFile $file)
{
$mime = $file->getMimeType();
$filename = $this->makeFileName();
$path = $this->getFullPath($this->directory . '/' . $filename);
$success = Image::make($file->getRealPath())
->resize($this->size, $this->size, true, false)
->save($path, $this->quality);
if (! $success) {
return false;
}
return $this->getJsonBody($filename, $mime, $path);
}
}
Here is UploadServiceProvider.php
namespace Tippy\Providers;
use Illuminate\Support\ServiceProvider;
use Tippy\Services\Upload\ImageUploadService;
class UploadServiceProvider extends ServiceProvider
{
public function register()
{
$this->app['upload.image'] = $this->app->share(function ($app) {
return new ImageUploadService($app['files']);
});
}
}
Here's my ImageUpload.php Facade
protected static function getFacadeAccessor()
{
return 'upload.image';
}
And finally I've autoloaded the provider
'Tippy\Providers\UploadServiceProvider',
And aliased the class
'ImageUpload' => 'Tippy\Facades\ImageUpload',
Any help would be much appreciated.
Before diving into the world of Facades & Services,
You have to take a look at PSR-0 convention. PSR-0 tells composer how to load your classes (facades, services & the lot).
Link to useful resources:
What is PSR-0
Using a PSR-0 Directory Structure
Setup your own library

Categories