Laravel: save image in database - php

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

Related

How to store imageable_id and imageable_type in photos table Laravel?

I have three tables in my database(users,cars and photos).
Users Table
Cars Table
Photos Table
My Models:
User.php
public function photo() {
return $this->morphOne('App\Models\Photo', 'imageable');
}
public function cars() {
return $this->hasMany('App\Models\Car', 'user_id');
}
Car.php
public function user() {
return $this->belongsTo('App\Models\User');
}
public function photo() {
return $this->morphOne('App\Models\Photo', 'imageable');
}
Photo.php
protected $path = '/storage/images/';
public function getFileAttribute($file) {
return $this->path . $file;
}
public function imageable() {
return $this->morphTo();
}
My Controller#store:
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('storage/images', $name);
$photo = Photo::create(['file' => $name]);
$input['photo_id'] = $photo->id;
}
$user->cars()->create($input);
return back();
Imageable_id and imageable_type aren't storing. Just NULL. Why? How to store it?
You're not using the relationship when you create the photo.
$photo = Photo::create(['file' => $name]);
It should be:
$photo = $user->photo()->create(['file' => $name]);
Also, $user->cars()->create(...) instead of $user->cars->create(...)

Cont: Url convert to string and save problem

This is my previous post: Laravel inserting normal image, value become null
Thank you for everyone giving me advise in previous post. Now I got another question. I would like to ask for help and teach me with this issues.
I currently want to save the image path in my database. As the previous post mentioned before. My database now is saving value 1 instead of the path. here is my function upload code.
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->image = \Storage::disk('public')->put('image', Request::file('image'));
$url = Storage::url('image');
$url= urldecode(string ($url));
$url->save();
$task->save();
return redirect('/');
}
I also want to display this in my welcome.blade.php. So, what would I add and change?
This is all my code:
public function index()
{
$user = Auth::user();
return view('welcome',compact('user'));
}
public function add()
{
return view('add');
}
public function create(Request $request)
{
$task = new Task();
$task->description = Request::get('description');
$task->user_id = Auth::id();
$flagInserted = \Storage::disk('public')->put('image', Request::file('image'));
$url = '';
if ($flagInserted) {
$url = Storage::url('image');
}
$task->image = $url;
$duplicate = Task::where('description',Request::get('description'))->first();
if($duplicate)
{
print_r("The data is exists");
}
else
{
$task->save();
}
return redirect('/');
}
public function edit(Task $task)
{
if (Auth::check() && Auth::user()->id == $task->user_id)
{
return view('edit', compact('task'));
}
else {
return redirect('/');
}
}
public function update(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->description = Request::get('description');
$task->save();
return redirect('/');
}
}
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$flagInserted = \Storage::disk('public')->put('image', Request::file('image'));
$url = '';
if ($flagInserted) {
$url = Storage::url('image');
}
$task->image = $url;
$task->save();
return redirect('/');
}
}
public function storeTask(){
$task= new Task();
$task->name = request('name');
$task->description = request('description');
$task->image = request('image');
$task->save();
return redirect('/task');
}
I have read the Laravel page. But not really sure and how can I able solve this problem.
below will return 1 or 0, if file is saved or not. That's why it is inserting 1 into your databse:
\Storage::disk('public')->put('image', Request::file('image'))
Once successfully saved, To fetch file url, you can use below code:
$url = \Storage::url('file.jpg');
So your code will be:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileuploadController extends Controller
{
//
public function index() {
return view('fileupload');
}
public function save(Request $request) {
$image = $request->file('image');
$fileName = time() . '.' . $image->getClientOriginalExtension();
$img = \Image::make($image->getRealPath());
$img->stream(); // <-- Key point
$flagInserted = \Storage::disk('public')->put($fileName, $img);
$url = '';
if ($flagInserted) {
$url = \Storage::url('app/public/' . $fileName);
}
dd($url);
}
}
If you face error like 'Class Image' not found that do as follow:
composer require intervention/image
You file will be saved in 'storage/app/public folder'.
If you file is not saved than please permission and allow permission your project folder.
have you try this.? Request::file to $request->file
and
replce Illuminate\Support\Facades\Request to use Illuminate\Http\Request;
ref link https://laravel.com/docs/6.x/filesystem#file-uploads here you can see
use Illuminate\Http\Request; is imported not Illuminate\Support\Facades\Request
public function upload(Request $request, Task $task)
{
if (isset($_POST['delete'])) {
$task->delete();
return redirect('/');
} else {
$task->image = \Storage::disk('public')->put('image', $request->image);
$task->save();
return redirect('/');
}
}
ref link https://laravel.com/docs/6.x/filesystem#storing-files
and to print image inside blade
you can use Storage::url() function on laravel
EX : Storage::url($task->image) // here image value is coming from task table data
ref link https://laravel.com/docs/6.x/filesystem#file-urls

how to solve the problem of file does not exist in laravel

I am using a observer class to store image, everything works fine e.g. images are store in public folder, save in database but after the saving it will give me a error like below
I tried this in my Student observer class
protected $request;
public function __construct(Register $request)
{
$this->request = $request;
}
public function created(Student $student)
{
//
}
public function creating(Student $student)
{
//dd($request->image);
if ($this->request->hasFile('image')) {
$file = $this->request->image;
$destinationPath = public_path().'/images/';
$filename= $student->username . '.'.$file->clientExtension();
$file->move($destinationPath, $filename);
$student->image=$filename;
}
}
And in my controller
public function create(Register $request)
{
$student=new Student;
$student->name = $request->input('name');
$student->username = $request->input('username');
$student->email = $request->input('email');
$student->password = bcrypt($request->input('password'));
$student->gender = $request->input('gender');
$student->phone = $request->input('phone');
$student->save();
$student->subjects()->attach($request->id);
return home('home');
}

Laravel Image Intervention bug

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

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

Categories