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'));
}
Related
//here is my controller
public function edituser(Request $request,$id){
$user=User::find($id);
$user->name=$request->name;
$user->email=$request->email;
$user->role_id=$request->role_id;
$users=User::all();
return view('edit',compact('users'));
}
//here is blade
<form action="{{route('edituser',['id'=>$user->id])}}" method="post">
#csrf
<div class="form-row align-items-center">
<div class="col-auto">
<label class="sr-only" for="inlineFormInput">Adı</label>
<input type="text" value="" class="form-control mb-2" id="inlineFormInput" placeholder="Adı">
</div>
<div class="col-auto">
<label class="sr-only" for="inlineFormInputGroup">Emaili</label>
<div class="input-group mb-2">
<input type="text" class="form-control" id="inlineFormInputGroup" placeholder="Emaili">
</div>
</div>
<select class="mdb-select md-form">
#foreach ($users as $user)
<option>--Səlahiyyət seç---</option>
<option value="1">{{$user->name}}</option>
#endforeach
</select>
//here is route
Route::get('edit/{id}','AdminController#edit')->name('edit');
Route::post('edituser/{id}','AdminController#edituser')->name('edituser');
Update: here is my all controller
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function delete($id){
$delete=User::where('id',$id)->delete();
if($delete){
return redirect()-> back();
}
}
public function edit(){
$users=User::all();
return view('edit',compact('users'));
}
public function edituser(Request $request,$id){
$user=User::find($id);
$user->name=$request->name;
$user->email=$request->email;
$user->role_id=$request->role_id;
}
It seems like you are using the wrong method on the controller.
The edituser method is used by the POST route, so you should have users/compact code on the edit method instead, as that is being used by the GET route.
Move the following code from edituser and put it into edit
$users = User::all();
return view('edit',compact('users'));
Your edituser method should probably look like:
public function edituser(Request $request,$id){
$user = User::find($id);
$user->name=$request->name;
$user->email=$request->email;
$user->role_id=$request->role_id;
return view('edit',compact('user'));
}
Please update your original answer to show both methods.
public function edit($id) {
$user = User::find($id);
$users = User::all();
return view('edit')->with(compact('user', 'users'));
}
public function edituser(Request $request, $id) {
$user = User::find($id);
$user->name = $request->name;
$user->email = $request->email;
$user->role_id = $request->role_id;
$users = User::all();
return view('edit')->with(compact('user', 'users'));
}
Hope fully it will help to you easily.
I am unable to find the issue. It is showing 404|Not Found
update.blade.php
#extends('main')
#section('content')
<h1>Update Post</h1>
<form method="POST" action="{{route('posts.update', $post) }}" >
#method('PUT')
#csrf
<input type="text" name="title"><br><br>
<input type="text" name="body"><br><br>
<button type="submit" class="btn btn-primary">Update</button>
</form>
#endsection
PostController.php (a resource controller)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\posts;
use Sessions;
class PostController extends Controller
{
public function index()
{
$post = posts::all();
return view('post.index', compact('post');
}
public function create(Request $req)
{
return view('posts.create');
}
public function store(Request $request)
{
$post = new posts;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('/');
}
public function show($data)
{
$post = posts::findOrFail($data);
return view('posts.read', compact('post','$post'));
}
public function edit(posts $post)
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, $id)
{
$request->validate([
'title'=>'required',
'body'=>'required'
]);
$post = posts::find($id);
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->save();
return redirect('/');
}
}
route:
Route::resource('posts', 'PostController');
please tell me what is the issue in this.
one of the advice I got is to change the name of view file i.e update.blade.php to edit.blade.php. I don't know how does it help
The problem is that you are returning the view: view('post.edit').
But you say that the file is called update.blade.php.
So you will have to rename the file to edit.blade.php or you need to change your edit function as follows, so that it returns the update blade file:
public function edit(posts $post)
{
return view('posts.update', compact('post'));
}
First you should change edit.blade.php instead of update.blade.php
Second you should not call model like this use App/posts; It is wrong. It must be use App\Post; in your PostController
Third you should change edit() in your controller
public function edit($id)
{
$post = Post::find($id);
return view('posts.edit', compact('post'));
}
You should use $post->id instead of $postin your form action
#extends('main')
#section('content')
<h1>Update Post</h1>
<form method="POST" action="{{route('posts.update', $post->id) }}" >
#method('PUT')
#csrf
<input type="text" name="title"><br><br>
<input type="text" name="body"><br><br>
<button type="submit" class="btn btn-primary">Update</button>
</form>
#endsection
Then check
public function update(Request $request, $id)
{
dd($id);//check id before update
$request->validate([
'title'=>'required',
'body'=>'required'
]);
$post = posts::find($id);
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->save();
return redirect('/');
}
I have multiple fields in my users table in laravel but i want to delete only image from users table, Please let me know the process.
Here are my usercontroller.php file..
public function userprofile(Request $request)
{
$user = DB::table('users')->where('id',Auth::user()->id)->get();
//dd($user);
$userWish = DB::table('package_wishlist')->where('user_id',Auth::user()->id)->where('is_active',1)->count();
$userComp = DB::table('package_comparison')->where('user_id',Auth::user()->id)->where('is_active',1)->count();
$bookings = DB::table('agent_bookings')
->where('cust_email',Auth::user()->email)->get();
return view('user/profile',['bookings'=>$bookings,'user'=>$user[0],'userWish'=>$userWish,'userComp'=>$userComp]);
}
public function imagedestroy($id)
{
$image = DB::table('users')->where('id', $id)->get();
$file= $image->user_image;
$filename = public_path().'/uploads/user_uploads/'.$image;
File::delete($filename);
}
And here is my profile.blade.php file..
#foreach($user as $delimage)
<a onclick="event.preventDefault();
document.getElementById('delete-image-form').submit();"
class="btn btn-default btn-sm btn-block">Delete</a>
<form id="delete-image-form" method="POST" action="{{
route('delimage.imagedestroy', $delimage->id) }}"
style="display: none;">
#method('DELETE')
#csrf
</form>
#endforeach
And my web.php file is this...
Route::get('/userprofile', 'CustomHomeController#userprofile')->name('userprofile');
Route::get('/userprofile/{id}', 'CustomHomeController#imagedestroy')->name('imagedestroy');
use first() instead of get(). get() gives you a collection which you need to iterate to get an attribute. so you just can't get image of a user like
$image = DB::table('users')->where('id', $id)->get();
$file= $image->user_image; //this won't work.
Try like
public function imagedestroy($id)
{
$image = DB::table('users')->where('id', $id)->first();
$file= $image->user_image;
$filename = public_path().'/uploads/user_uploads/'.$image;
File::delete($filename);
}
And your userprofile method should be like
public function userprofile(Request $request)
{
$user = DB::table('users')->where('id',Auth::user()->id)->first();
//dd($user);
$userWish = DB::table('package_wishlist')->where('user_id',Auth::user()->id)->where('is_active',1)->count();
$userComp = DB::table('package_comparison')->where('user_id',Auth::user()->id)->where('is_active',1)->count();
$bookings = DB::table('agent_bookings')
->where('cust_email',Auth::user()->email)->get();
return view('user/profile',['bookings'=>$bookings,'user'=>$user,'userWish'=>$userWish,'userComp'=>$userComp]);
}
So you don't need to iterate in view. just use
<a onclick="event.preventDefault();
document.getElementById('delete-image-form').submit();"
class="btn btn-default btn-sm btn-block">Delete</a>
<form id="delete-image-form" method="POST" action="{{
route('imagedestroy', $user->id) }}"
style="display: none;">
#method('DELETE')
#csrf
</form>
I'm trying to post an image from a one to many relationship while also doing the CRUD (create part), but I am having some trouble doing it. I keep on getting this error
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given, called in
Whenever I try to use associate to define the relationship together with user_info with user_image table. I have already used the array function to make it into an array but it still gave me this error. So what should I do?
createController:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($file = $request->hasFile('input_img')) {
$file = array();
$file = $request->file('input_img') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create($file);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
#foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->signature !!}">
#endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</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>
You should give an array while passing data to create method like this. Currently, you are passing the file object.
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
I am having some trouble doing a one to one relationship with user_info table and userImage table. When I try to upload my image, it didn't save into my database and it user_id is 0. I managed to successfully do a one to many and one to one relationship in the past but not with CRUD together. Can anyone help me? Best to give me some example for me to refer or advice on what should I do. Thanks in advance
Here are my current codes:
createController:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalName();
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
#foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->userImage!!}">
#endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</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>
You need to check out Laravel relations to clean up that code and simplify a lot of steps.
Change this line
$UserImage->user_infos()->associate($user_info);
For this
$UserImage->user_id = $user_info;
Take in mind that you're overriding the value of $UserImage inside that method.