How i can Delete image from users table in Laravel? - php

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>

Related

how making many submit button in one page laravel 8

I have several buttons to insert data into the database, but only one command works, while the others don't work, what should I do, I will give an example of the data I created
this is my controller :
public function store(Request $request)
{
//
$days = $request->hari;
$hours = $request->jam;
$minutes = $request->menit;
$model = new Q_Topic_User;
$model->status = $request->status;
$model->topic_id = $request->topic_id;
$model->timer = Carbon::now()->addDays($days)->addHours($hours)->addMinute($minutes);
$topik = $request->topic_id;
$model->user_create = auth()->id();
// dd($request->all());
$model->save();
return redirect('qanswers/'. $topik);
}
public function storeAns(Request $request)
{
$modellama = Q_Answer::where('user_create', '=', $request->kode_user)
->Where('topic_id', '=', $request->topic_id)
->Where('question_id', '=', $request->question_id);
$a = $request->user_answer;
$b = $request->answer;
if ($a === $b){
$nilai = "1";
}
else{
$nilai = "0";
}
if ($modellama >= "1"){
$modellama->delete();
}
// dd($request->all());
$model = new Q_Answer;
$model->topic_id = $request->topic_id;
$model->question_id = $request->question_id;
$model->user_answer = $request->user_answer;
$model->answer = $request->answer;
$model->hasil = $nilai;
$model->user_create = auth()->id();
$topik = $request->topic_id;
$model->save();
return redirect('qanswers/'. $topik);
}
public function storeTot(Request $request)
{
$tot_nilai = Q_Answer::select(DB::raw("CAST(SUM(hasil) as int) as tot_nilai"))
->Where('topic_id', '=', $request->topic_idi)
->Where('user_create', '=', auth()->id())
->pluck('tot_nilai');
// dd($tot_nilai);
$tot_soal = Q_Question::select(DB::raw("CAST(COUNT(topic_id) as int) as tot_soal"))
->Where('topic_id', '=', $request->topic_idi)
->pluck('tot_soal');
dd($request->all());
$model = new Q_Answer_Tot;
$model->topic_id = $request->topic_idi;
$model->totalsoal = $tot_soal;
$model->totalnilai = $tot_nilai;
$model->user_create = auth()->id();
// dd($request->all());
$model->save();
$topik = $request->topic_id;
return redirect('qanswers/'. $topik);
}
blade :
<form method="POST" action="{{ url('qanswers') }}"
enctype="multipart/form-data">
#csrf
#foreach ($datas as $d_value)
<button type="submit" class="btn btn-sm bg-success">Kirim data</button>
#endforeach
</form>
<form method="POST" action="{{ url('qanswers.storeAns') }}"
enctype="multipart/form-data">
#csrf
#foreach ($questionss as $q_value)
<button type="submit" class="btn btn-sm bg-success">Kirim Pilihan Pertanyaan</button>
#endforeach
</form>
<form method="POST" action="{{ url('qanswers.storeTot') }}"
enctype="multipart/form-data">
#csrf
#foreach ($questionss as $t_value)
<button type="submit" class="btn btn-sm bg-success">Kirim Pilihan Peserta</button>
#endforeach
</form>
my web.php :
Route::resource('/qanswers', Q_AnswersController::class);
Route::post('/storeAns',[Q_AnswersController::class, 'storeAns'])->name('storeAns');
Route::post('/storeTot',[Q_AnswersController::class, 'storeTot'])->name('storeTot');
i can save data in store but i can save data using storeAns and storeTot. I dont find error in laravel log but i can see my data using dd($request->all()); can u help me?
Its good practice to give each form an unique id. With multiple forms and buttons, I would specify the form for the button. And you need to use value to figure out which button was pressed, especially when you are going to the same url in more than one form.
<form method="POST" id="answers" action="{{ url('qanswers') }}"
enctype="multipart/form-data">
#csrf
#foreach ($datas as $d_value)
<button type="submit" class="btn btn-sm bg-success" value="form1">Kirim data</button>
#endforeach
</form>
<form method="POST" id="storeans1" action="{{ url('qanswers.storeAns') }}"
enctype="multipart/form-data">
#csrf
#foreach ($questionss as $q_value)
<button type="submit" class="btn btn-sm bg-success" value="form2">Kirim Pilihan Pertanyaan</button>
#endforeach
</form>
<form method="POST" id="storeans2" action="{{ url('qanswers.storeAns') }}"
enctype="multipart/form-data">
#csrf
#foreach ($questionss as $q_value)
<button type="submit" class="btn btn-sm bg-success" value="form3">Kirim Pilihan Pertanyaan</button>
#endforeach
</form>
I have shown the value with formx. SInce you are creating many buttons for each form, each should have an unique value such as
form1btn1
form1btn2
form1btn3

Trying to create a ban button in Laravel. Don't get any error just get not found - Laravel 8

here is my controller method
public function blockUser(User $user)
{
$user = User::findOrFail($user->id);
$user->blocked_at = Carbon::now();
$user->save();
return Redirect()->route('admin.users.index')->with('User has been blocked');
}
This is my web.php
Route::group(['middleware' => ['admin']], function () {
Route::get('/admin', [App\Http\Controllers\HomeController::class, 'adminView'])->name('admin.view');
Route::get('/admin/users', [App\Http\Controllers\UserController::class, 'index'])->name('admin.users.index');
Route::delete('/admin/users/{user}', [App\Http\Controllers\UserController::class, 'adminDelete'])->name('admin.users.destroy');
Route::get('/admin/posts', [App\Http\Controllers\AdminController::class, 'index'])->name('admin.posts.index');
Route::put('/admin/users/{users}', [App\Http\Controllers\UserController::class, 'blockUser'])->name('admin.users.ban');
});
This is my blade
<td>
<button type="button" class="btn btn-sm btn-outline-danger" onclick="event.preventDefault(); document.getElementById('ban-user-from-{{ $user->id }}').submit()">
<i class="fas fa-ban" title="Ban"></i>
</button>
<form id="ban-user-from-{{ $user->id }}" action="{{ route('admin.users.ban', [$user->id]) }}" method="POST" style="display: none">
#csrf
#method("PUT")
</form>
</td>
I have a blocked_at column in my database and have done the functionality on the middleware and kernel. If I add today date manually into the database for that field the user is blocked and a message comes up when they try to login. However I am now trying to create a button for the admin panel so that an admin can just block a user.
Change your controller :
public function blockUser(Request $request)
{
$user = User::findOrFail($request->users);
$user->blocked_at = Carbon::now();
$user->save();
return Redirect()->route('admin.users.index')->with('User has been blocked');
}

Pass id from controller index to store - Laravel

This is my route :
Route::post('/store', 'EditlinkController#store');
My controller
public function index()
{
$id = $_GET['id'];
$links = DB::table('slugs')->where('slugs.id',$id)
->join('links','links.sid','=','slugs.id')
->get();
return view('editlink', ['links' => $links]);
}
public function store(Request $request, $id)
{
$url = $request->input('url');
$data =new link;
$sid = $id;
$data->sid = $sid;
$data ->url = $url;
$data ->save();
return redirect('/links');
}
And my view:
<form role="form" method='POST' action="{{url('store')}}">
<div class="entry input-group col-xs-3">
<input class="form-control" name="url" type='url' placeholder="https://..." size="100"/>
<input type="hidden" name="_Token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-primary" type="button">
<span class="material-icons md-12">add</span>
</button>
{{ csrf_field() }}
</div>
</form>
So basically here I want to call $id from index to store. I also have tried
Route::post('/store/{id}', 'EditlinkController#store');
But still doesn't work. Thank you.
Your route, /store/{id}, requires you to have a route parameter. Make sure you have an $id available to you before you generate your url for your form.
An example of what your open form tag should look like with the $id included:
<form role="form" method='POST' action="{{url('store', $id)}}">
I'm assuming the view editlink is where the markup for the form resides. If so, then you can simply pass the value of the id to your view from your controller:
return view('editlink', ['links' => $links, 'id' => $id]);

Laravel - set session from form input

I cannot display session value in my view. I only want to display it to see if it's correctly set inside the controller. Is it correctly set in controller? How can I check?
I have this in view:
<div class="panel panel-success">
<form action="{{ route('get_table') }}" method="POST">
{{ csrf_field() }}
#foreach($tables as $data)
<button type="submit" name="tables" class="btn btn-primary" value="{{ $data->id }}">
{{$data->name }}
</button>
#endforeach
</form>
{{ Session::get('table_id') }}
</div>
This in ListController:
public function index() {
$tables = DB::table('tables')->get();
return view('welcome', compact('tables'));
}
public function getTable(Request $request) {
$table_id = $request->get('tables');
$request->session()->put('table_id', $table_id);
}
And this in web.php routes:
Route::get('/', 'ListController#index')->name('get_table');
Route::post('/', 'ListController#getTable');
I even tried
public function getTable(Request $request) {
$request->session()->put('table_id', '1234');
}
Nothing shows up in the view at {{ Session::get('table_id') }}
What am I doing wrong?
You can try this:
public function getTable(Request $request) {
$table_id = $request->get('tables');
return redirect()->back()->with('table_id',$table_id);
}
if you want to redirect to specific route then:
public function getTable(Request $request) {
$table_id = $request->get('tables');
return redirect()->route('RouteName')->with('table_id',$table_id);
}
and then in view:
#if(Session::has('table_id'))
{{ Session::get('table_id') }}
#endif
Hope you got your answer

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'));
}

Categories