Laravel: Can't get uploaded images to display - php

On my website, a registered user can create a post by uploading an image and writing a description. I have made it where a unique image name is created based on the user's image name and the time they upload the image. Once a name is created it is stored in the post database. The image name successfully gets stored and so does the actual image. However, when it comes to actually displaying the image on the post nothing comes up like it can't find the image. I can't seem to figure out why this is.
Here is my PostController.php class:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostController extends Controller
{
public function getDashboard(){
$posts = Post::orderBy('created_at', 'desc')->get();
return view('dashboard', ['posts' => $posts]);
}
public function postCreatePost(Request $request){
$this->validate($request, [
'body' => 'required',
'cover_image' => 'image|nullable|max:1999'
]);
if($request->hasFile('cover_image')){
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('cover_image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
} else{
$fileNameToStore = 'noimage.jpg';
}
$post = new Post();
$post->body = $request['body'];
$post->cover_image = $fileNameToStore;
$message = 'There was an error';
if($request->user()->posts($post)->save($post)){; //points here
$message = 'post successfully created';
}
return redirect()->route('dashboard')->with(['message' => $message]);
}
public function getDeletePost($post_id){
$post = Post::where('id', $post_id)->firstOrFail();
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'post deleted']);
}
}
Here is my view:
<section class="row new-post">
<div class="col-md-6 col-md-offset-3">
<form action="{{ route('postcreate') }}" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="cover_image" class="form-control" id="cover_image">
</div>
<div class="form-group">
<textarea class="form-control" name="body" rows="5" placeholder="your post"></textarea>
</div>
<button type="submit" class="btn btn-primary">Create post</button>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</div>
</section>
#foreach($posts as $post)
<section class="row posts">
<div class="col-md-6">
<article class="post">
<p>{{ $post->body }}</p>
<div class="info">Posted by {{ $post->user->first_name }} {{ $post->user->last_name }} on {{ $post->created_at }}</div>
<div class="interaction">
Like|
#if(Auth::user() == $post->user)
Edit|
Delete
#endif
</div>
</article>
</div>
<div class="col-md-6">
<img src="/storage/cover_images/{{ $post->cover_image }}">
</div>
</section>
#endforeach
Here is my migration:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('cover_image');
$table->text('body');
$table->integer('user_id');
});

You're storing as public/cover_images but echoing out storage/cover_images.
Updated following your response;
Why not try using
<img src="{{ asset('storage/cover_images/' . $post->cover_image) }}">

Related

I'm stuck for 2 days with probably an obvious thing - PHP + Laravel image update

I started creating an e-commerce platform and I'm stuck with a problem I can't solve for 2 days.. It's probably something obvious but I just can't find the solution for this. Could you help me with this, please? I get this error:
Missing required parameters for [Route: images.update] [URI: dashboard/images/{image}]. (View: C:\xampp\htdocs\ecommerce\ecommerce\resources\views\website\admin\product_image\update.blade.php)
update.blade.php
#extends('website.admin.layouts.main')
#section('content')
<div class="col-md-12 col-sm-12 ">
<div class="x_panel">
<div class="x_title">
<h2>Zaktualizuj obraz</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
<form id="updateimage-form" data-parsley-validate="" class="form-horizontal form-label-left" novalidate="" enctype="multipart/form-data" method="POST" action="{{route('images.update', $productImage->id)}}">
#csrf
#method('PUT')
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Produkt<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<select class="form-control" name="product_id">
#foreach ($product as $prodcat)
<option value="{{$prodcat -> id}}" name="product_id">{{ $prodcat -> product_name }}</option>
#endforeach
</div>
</div>
<div class="ln_solid"></div>
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Nazwa obrazu<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<input type="text" id="img_title" name="img_title" placeholder="Image Title" value="{{ $productImage -> image_name }}" required="required" class="form-control ">
</div>
</div>
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Wgraj obraz<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<input type="file" name="img" id="img" onchange="fileSelected();"/>
</div>
</div>
<div class="item form-group">
<div class="col-md-6 col-sm-6 offset-md-3">
<button class="btn btn-primary" type="reset">Wyczyść</button>
<button type="submit" class="btn btn-success">Zaktualizuj obraz</button>
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
models\ProductImage.php
<?php
namespace App\Models\models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ProductImage extends Model
{
protected $fillable = [
'product_id',
'image_name',
'image',
'slug',
'status'
];
public function product()
{
return $this -> belongsTo('App\Models\models\Product');
}
}
ProductImageController.php
<?php
namespace App\Http\Controllers;
use App\Models\models\Product;
use App\Models\models\ProductImage;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class ProductImageController extends Controller
{
public function index()
{
$productImage = ProductImage::all();
return view('website.admin.product_image.index', compact('productImage'));
}
public function create()
{
$product = Product::all();
return view('website.admin.product_image.create', compact('product'));
}
public function store(Request $request)
{
$slug = Str::slug($request->image_name, '-');
$image = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $image);
ProductImage::create([
'image_name'=>$request->image_name,
'image'=>$image,
'product_id'=>$request->product_id,
'slug'=>$slug,
]);
return redirect()->route('images.index');
}
public function show(ProductImage $ProductImage)
{
//
}
public function edit(ProductImage $productImage)
{
$product = Product::all();
return view('website.admin.product_image.update',compact('productImage','product'));
}
public function update(Request $request, ProductImage $productImage)
{
$slug=Str::slug($request->image_name,'-');
if($request->image)
{
$image = time() .'.'. $request -> image -> extension();
$request->image->move(public_path('images'), $image);
}
else
{
$image=$productImage->image;
}
$productImage->update([
'image_name'=>$request->image_name,
'image'=>$image,
'product_id'=>$request->product_id,
'slug'=>$slug,
]);
return redirect()->route('images.index');
}
public function destroy(productImage $productImage)
{
$productImage->delete();
return redirect()->route('images.index');
}
}
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('website.shop.layouts.main');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/dashboard', [App\Http\Controllers\DashboardController::class, 'index'])->name('dashboard.index');
Route::resource('/dashboard/categories', 'App\Http\Controllers\ProductCategoryController');
Route::resource('/dashboard/product', 'App\Http\Controllers\ProductController');
Route::resource('/dashboard/images', 'App\Http\Controllers\ProductImageController');
update.blade.php
<form method="post" action="{{route('images.update', $productImage->id)}}" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group">
<label for="filename">Select your Image</label>
<input type="file" name="image" class="form-control">
<button type="submit" class="btn btn-primary btn-lg">Update</button>
</div>
</form>
ProductImageController.php
<?php
namespace App\Http\Controllers;
use App\Models\models\ProductImage;;
use Illuminate\Http\Request;
class DocumentController extends Controller
{
public function update(Request $request, $productId){
$product = ProductImage::findOrFail($productId);
if($request->hasfile('image'))
{
$file = $request->file('image');
$name=$file->getClientOriginalName();
$file->move(public_path().'/uploads/ProductImages/', $name);
$file = $name;
$product->image = $file;
}
$product->save();
return redirect()->back();
}
}
I solved this, the problem was with "images" name in route. I changed it to something else everywhere and it works now.
action="{{route('images.update', $productImage->id)}}" is incorrect way of calling route() helper function. Consider the following snippet;
action="{{route('images.update', [
'image' => $productImage->id
])}}"
For more details about route() helper, see this link; https://laravel.com/docs/8.x/helpers#method-route
You don't have Model Binding happening here you have Dependency Injection happening instead. For Implicit Route Model Binding to take place you have to match the type hinted parameter of your method to the name of the route parameter. In your case the route parameter is named image, not productImage. So you are getting an empty new instance of ProductImage instead of the replacement for the Route Model Binding.
Change your controller's parameter to match the route parameter:
vvvvv
public function edit(ProductImage $image)
You would need to change this in all the methods you want the Implicit Binding for, unless you want to override the parameter used in the route.
vvvvv
public function update(Request $request, ProductImage $image)
At the moment you are passing an empty model to your view which is then trying to use it's "id" to generate a route, but "id" is null and route parameters can no to null.

how to save the image name in the database so that you can view it later?

here the user transfers the photo from the device to the form
it is necessary that when registering a user he entered a photo and this photo could be viewed by the administrator in the admin area
web.php
Route::post('/head', 'ImageController#upload')->name('image.upload');
ImageController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ImageController extends Controller
{
public function upload(Request $request)
{
$path = $request - file('image')->store('upload', 'public');
return view('default',['path'=> $path]);
}
}
(php artisan storage:link) entered
input form
<div class="form-group row">
<label for="ydostak" class="col-md-4 col-form-label text-md-right">{{ __('Фото удостоверение с двух сторон') }}</label>
<form action{{ route('image.upload')}}="" method="post" accept-charset="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<input type="file" name="image">
</div>
</form>
</div>
withdrawal form
#isset ($path)
<img class="img-fluid" scr="{{asset('/storage/'. $path)}}" alt="">
#endisset
public function upload(Request $request)
{
$user = new user ;
if($request->hasFile('image')){
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Image::make($image)->resize(300, 300)->save( storage_path('/uploads/' . $filename ) );
$user->image = $filename;
$user->save();
};
$user->save();
return redirect()->route('user.index')
->with('success','User created successfully');
}
Your form tag is incorrectly formed:
<form action{{ route('image.upload')}}="" method="post" accept-charset="multipart/form-data">
You are not assigning anything to the action as what you have isn't the action attribute. You have something like this:
<form actionhttp://yoursite/head="" ...>
Which isn't the action attribute. You want:
<form action="{{ route('image.upload') }}" ...>
Which will give you something like:
<form action="http://youriste/head" ...>
Once you fix that you can move onto actually dealing with your Controller method.

Method App\Http\Controllers\SkillController::show does not exist. - Laravel 5.7

I keep getting this error, when I try to create a skill on my project
Method App\Http\Controllers\SkillController::show does not exist.
I don't need a show() method because I don't need a show view of my skill object.
This is my route block look like
//Skill
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
This is my entire SkillController
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Skill;
use Input, View, File, Image, SSH, Redirect,Response;
class SkillController extends Controller {
public function index(){
$skills = Skill::orderBy('updated_at', 'desc')->orderBy('created_at', 'asc')->where('img_path','==',NULL)->get();
$first_color = $skills[0]->color_code;
$second_color = $skills[1]->color_code;
$third_color = $skills[2]->color_code;
$fourth_color = $skills[3]->color_code;
$fift_color = $skills[4]->color_code;
return View::make('layouts.be.skills.index', get_defined_vars());
}
public function all(){
return Skill::all()->pluck('name');
}
public function create(){
$skillTypes = ['Build System','Development Environment','Server Management','Operating System','IDE','Creative Suite','Video Editing','Package Management','Git Repository','Web Scaffolding','CSS Precompiler','Scripting','Framework','DBMS','Unit Test','Automation Testing','Cloud Platform','Hosting Provider','Content Management', 'API', 'Authentication' , 'Integration','Language','Web Server','Project Managment','Documentation','Utility','Network Analyzer' ];
sort($skillTypes);
return View::make('layouts.be.skills.create', get_defined_vars());
}
public function edit($id){
$skillTypes = ['Build System','Development Environment','Server Management','Operating System','IDE','Creative Suite','Video Editing','Package Management','Git Repository','Web Scaffolding','CSS Precompiler','Scripting','Framework','DBMS','Unit Test','Automation Testing','Cloud Platform','Hosting Provider','Content Management', 'API', 'Authentication' , 'Integration','Language','Web Server','Project Managment','Documentation','Utility','Network Analyzer' ];
sort($skillTypes);
$skill = Skill::findOrFail($id);
return View::make('layouts.be.skills.edit', get_defined_vars());
}
public function store(){
$skill = new Skill;
$skill->type = Input::get('type');
$skill->name = Input::get('name');
$skill->value = Input::get('value');
$skill->color_code = Input::get('color_code');
$skill->save();
if (Input::hasFile('logo_path')) {
$image_path = '/assets/img/skill/';
$path = public_path() . $image_path;
$file = Input::file('logo_path');
$img_name = $skill->id.'.png';
$uploadSuccess = $file->move($path, $img_name);
$file_path = $path . $img_name;
$skill->img_path = $image_path . $img_name;
$crop_file = Image::make($file_path)->fit(20,20);
$crop_file->save($path . 'crop-'.$img_name, 65);
}else {
$skill->img_path = Input::get('logo_path');
}
$skill->save();
return Redirect::to('/skill') ->with('success','The skill was created succesfully!');
}
public function update($id){
$inputs = Input::all();
$skill = Skill::find($id);
$skill->name = Input::get('name');
$skill->type = Input::get('type');
$skill->value = Input::get('value');
$skill->color_code = Input::get('color_code');
$skill->save();
if (Input::hasFile('logo_path')) {
$image_path = '/assets/img/skill/';
$path = public_path() . $image_path;
$file = Input::file('logo_path');
$img_name = $skill->id.'.png';
$uploadSuccess = $file->move($path, $img_name);
$file_path = $path . $img_name;
$skill->img_path = $image_path . $img_name;
$crop_file = Image::make($file_path)->fit(20,20);
$crop_file->save($path . 'crop-'.$img_name, 65);
} else {
$skill->img_path = Input::get('logo_path');
}
$skill->save();
return Redirect::to('/skill') ->with('success','The skill was updated succesfully!');
}
public function destroy($id){
$skill = Skill::find($id);
$skill->delete();
$image_path = '/assets/img/skill/';
$path = public_path() . $image_path;
File::deleteDirectory($path);
return Redirect::to('/skill') ->with('success','The skill was deleted succesfully!');
}
public function skilldata(Request $request){
$skill = str_replace("-"," ",$request->skill);
$data = Skill::where(DB::raw('LOWER(type)'),'=',$skill)->get();
return response()->json($data, 200);
}
}
I also tried this 2 commands already
┌──[root#bheng]──[/home/forge/bheng]
└── php artisan cache:clear
Application cache cleared!
┌──[root#bheng]──[/home/forge/bheng]
└── composer dumpauto
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> #php artisan package:discover
Discovered Package: nesbot/carbon
Discovered Package: laravel/slack-notification-channel
Discovered Package: laravel/nexmo-notification-channel
Discovered Package: laravelcollective/remote
Discovered Package: htmlmin/htmlmin
Discovered Package: intervention/image
Discovered Package: laravelcollective/html
Package manifest generated successfully.
You have new mail in /var/mail/root
┌──[root#bheng]──[/home/forge/bheng]
└──
skill.create.blade.php
#extends('layouts.be.master')
#section('content')
<div class="card-body card-padding">
<div class="row">
{!! Form::open(array('class' => 'form-horizontal', 'role' =>'form', 'url'=>'skill/store','files' => true)) !!}
<div class="col-sm-4">
{{-- Name --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" value="{{Request::old('name')}}" value="" name="name" class="form-control" id="name" placeholder="Name">
</div>
</div>
{{-- Type --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Type</label>
<div class="col-sm-10">
<select name="type" class="form-control">
#foreach($skillTypes as $item)
<option value="{{ $item }}">{{ $item }}</option>
#endforeach
</select>
</div>
</div>
{{-- Value --}}
<div class="form-group">
<label class="col-sm-2 control-label">Value</label>
<div class="col-sm-8">
<br>
<input type="range" id="range-value" value="93" name="value">
</div>
<div class="col-sm-2">
<h3 id="text-value"></h3>
</div>
</div>
{{-- Color --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Color</label>
<div class="col-sm-2">
<input type="color" name="color_code" class="form-control" placeholder="Color" id="example-color-input">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<a class="btn btn-default" href="/skill"> Cancel </a>
<button type="submit" class="btn btn-info">Create</button>
</div>
</div>
</div>
<div class="col-sm-8">
{{-- Icon --}}
<div class="form-group">
<label class="col-sm-2 control-label" >Icon</label>
<div class="col-sm-10">
<img name="logo_path" id="skill-icon" width="300px"><br><br>
<input type="file" class="form-control" name="logo_path" aria-describedby="fileHelp">
</div>
<label class="col-sm-2 control-label" >Icon URL </label>
<div class="col-sm-10">
<input id="url-logo" name="logo_path" type="text" class="form-control">
</div>
</div>
</div>
{!!Form::close()!!}
</div>
</div>
#stop
#section('custom-scripts')
<script type="text/javascript" src="/js/Vibrant.js"></script>
<script type="text/javascript">
function readLogo(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#skill-icon').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
// Update media preview with base64 image
$( "input[name*='logo_path']" ).change(function(){
readLogo(this);
});
$( "#url-logo" ).on('keyup',function(){
$('#skill-icon').attr('src', $( "#url-logo" ).val());
});
$('#text-value').text($('#range-value').val());
$('#range-value').change(function(){
$('#text-value').text($('#range-value').val());
});
// Icon
var icon = $('#skill-icon');
icon.attr('src', $( "#url-logo" ).val());
$( "#url-logo" ).on('keyup',function(){
var vibrant = new Vibrant(icon[0]);
var swatches = vibrant.swatches()
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch])
// console.log(swatches[swatch].getHex());
var color = swatches[swatch].getHex();
$( "input[name*='color_code']" ).val(color)
console.log('%c >>>>>>>>>>>>>>', "color:" + String(color) + ";");
console.log('color',color);
// Vibrant #3c62ac
// Muted #7484ab
// DarkVibrant #345cab
// DarkMuted #101010
// LightVibrant #849ccc
});
</script>
#stop
Please let me know if you spot anything I should not do.
It just route ordering issue.
Make Route Order Like This :
//Skill
Route::post('skill/store','SkillController#store');
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
Route::get('skill/{id}/edit', 'SkillController#edit');
OR
If your making CRUD module then use Laravel 'Resource Controllers' routing method https://laravel.com/docs/5.7/controllers#resource-controllers
First Create Resource Controller : Run Below command In terminal
php artisan make:controller SkillController --resource
Then Put Below Line In 'routes/web.php' file
Route::resource('skill', 'SkillController');
You don't have a method= on your
And that is why assume Route::resource set up it will assume you're trying to access the show method.
Form::open(array('url' => 'foo/bar', 'method' => 'POST'))
Yeah as I thought in my initial comment, you haven't specified an action for the form - this should resolve your issues:
{!! Form::open(array('class' => 'form-horizontal', 'role' =>'form', 'url'=>'skill/store', 'action' => 'SkillController#store' ,'files' => true)) !!}
also, your routes are incorrect - your routes should be:
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::patch('skill/{id}/update','SkillController#update'); //this should be put or patch not post
Route::delete('skill/{id}/destroy','SkillController#destroy');
if you already manually wrote routes like this
//Skill
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
then you dont need this one, this code should be somewhere on your routes
Route::resource('skills','SkillController');
or
you can remove your entire manual written routes of skillcontroller
change it into this one
Route::resource('skills', 'SkillController', ['only'=> ['index','create','store','delete','edit','update']]);

Undefined variable:user laravel

I keep on getting this error whenever I try to enter the upload page.
Can anybody help?
I have already done the compact part to make sure that the variable is being passed to the view and also my route should be ok I think.
I tried using dd but all it does is keep on showing me the error
Error: Undefined variable: user (View: C:\xampp\htdocs\Evaluation\resources\views\upload.blade.php)
Here are my codes:
upload.blade.php
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
UploadController:
public function upload(){
return view(‘upload’);
}
public function store(Request $request,$id){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
var_dump('has file '.$request->hasFile('file'));
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
// $Image->user_id = $id;
//$Image->save();
$user->find($id);
dd($user);
$user->Images()->save($Image);
}
return redirect('/home');
}
public function test(){
$user = user_information::where('id')->get();
return view('upload', compact('user'));
}
Route: (this are my route)
Route::get('/UploadUser/upload','UploadController#upload’);
Route::post('/UploadUser','UploadController#store');
Route::post('/UploadUser/upload', 'UploadController#test');
Another question: I keep on getting this error when i try to upload a file, so what should I do?
Here is the error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (form.images,
CONSTRAINT images_user_id_foreign FOREIGN KEY (user_id) REFERENCES
usere_information (id)) (SQL: insert into images (name,
size, user_id, updated_at, created_at) values (download.png,
4247, 1, 2017-10-25 08:54:57, 2017-10-25 08:54:57))
Image model:
class Image extends Model
{
protected $fillable = array('name','size','user_id');
public function user_informations() {
return $this->belongsTo('App\user_information', 'user_id', 'id');
}
}
Images table:
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('size');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user_informations');
$table->timestamps();
});
User_information table:
Schema::create('user_informations', function (Blueprint $table) {
$table->increments('id');
$table->engine = 'InnoDB';
$table->binary('signature');
$table->String('Name');
$table->timestamps();
});
User_information model:
class user_information extends Eloquent
{
protected $fillable = array('signature', 'Name');
protected $table = 'user_informations';
protected $primaryKey = 'id';
public function Images() {
return $this->hasOne('App\Image','user_id');
}
}
How to get the image?
Here is the view folder:
#foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
Edit<br>
#foreach ($data3 as $currentUser)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endforeach
#if($data3->count())
#foreach($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['id'=>$currentUser->user_id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
</a>
#endforeach
#else
<a href="{!! route('user.upload.image', ['id'=>$object->id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
#endif
#endforeach
HomeController:
public function getInfo($id) {
$data = user_information::where('id',$id)->get();
$data3=Image::where('user_id',$id)->get();
return view('test',compact('data','data3'));
Because you didn't pass the user to your upload view, try to pass it like this :
public function upload(){
$id = 1 //The wanted user or if the user is authenticated use Auth::id()
$user = User::find($id);
return view('upload')->withUser($user);
}
Or if the user is authenticated use Auth in the view :
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{auth()->id()}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
For the second problem it's because in the route you have
Route::post('/UploadUser','UploadController#store');
and the your store method signature is
public function store(Request $request,$id){
The $id parameter that did the problem because it's not defined in the route so simply remove it from the method signatre
public function store(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id; // here id is declared no need for the parameter
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
$Image->user_id = $id;
$Image->save();
}
return redirect('/home');
}
For the third case you have to change the routes from :
Route::get('/UploadUser/upload','UploadController#upload’);
to
Route::get('/UploadUser/{user}/upload','UploadController#upload’)->name('user.upload.image');
And in the view add the id in the upload button url maybe like this :
{!! route('user.upload.image', ['user'=>$currentUser->id]) !!}
Then in the upload method :
public function upload(user_information $user){ // route model binding here
// dd($user); //for testing only :)
return view('upload')->withUser($user);
}
In the view change
<input type="hidden" name="user_id" value="{{auth()->id()}}">
To
<input type="hidden" name="user_id" value="{{$user->id()}}">
And you are good to go ;)
#foreach ($data as $currentUser)
<b>Name: </b>{{ $currentUser->Name }}<br><br>
Edit<br>
#if($currentUser->Image)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endif
<a href="{!! route('user.upload.image', ['id'=>$currentUser->id]) !!}">
#endforeach
You have miss to pass id in your where condition,
public function test(){
$user = user_information::where('id',$id)->first();
return view('create1', compact('user'));
}
and you have to pass your user data into this,
public function upload(){
$user = user_information::where('id',$id)->first();
return view(‘upload’,compact('user'));
}
Hope it helps,
On your upload function, you have to pass the user variable because you use the $user in the view. So the controller will be
public function upload() {
$user = Auth::user();
return view('upload', compact('user'));
}
do not forget to change the $user based on your need.
You have to pass an $id variable into your test() method. Then please comment below what's the error next so I can follow you through.
Update
Since you don't want to pass an id. You can use:
public function test(){
$u = Auth::user();
$user = user_information::where('id', $u->id)->get();
return view('upload', compact('user'));
}
OR
Try to use first() instead of get().
More option:
I have noticed, you're using the upload() method here, why not passing the $user there? like so:
public function upload(){
$user = Auth::user();
return view(‘upload’, compact('user'));
}

Trouble printing out image from public folder laravel

I want to show the image that I had just uploaded and only show it to those who have uploaded it. For example, user table contain jack, Emily and John, so if jack were to upload a file the image will show directly under him, but I don't know how to do it?
This is how it look like now:
Controller: (how I store the image)
public function store1(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$userImage = new UserImage;
$userImage->name = $name;
$userImage->size = $size;
//dd($userImage);
$userImage->save();
}
view.blade.php
#foreach ($data as $object)
<b>Name: </b>{{ $object->name }}<br><br>
#endforeach
I saw people using this inside their blade.php, but I don't know what the $model is:
<img src="{{ asset('public/images/' . $model->image) }}">
Upload.blade.php (this is my upload page where user will upload their image)
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
There are many ways to do it.
You could either use Eloquent or using query builder of Laravel.
In your controller you should get all the images that the user uploaded.
Query builder approach :
//don't forget the namespace
`use DB;`
//in your function write this.
$images = DB::table('user_images')
->join('users', 'users.id', '=', 'user_images.user_id')
->where('users.id', '=', $id)
->get();
//use dd($images) to verify that the variable $images has data
//send $images in your view
in your view write a foreach loop like so:
#foreach($images as $image)
<img src="{{ asset('public/images/' . $image->name ) }}">
#endforeach

Categories