My All Data has been updated successfully but Image not update and old image not remove. I am using Query Builder.
Can anyone tell me what to do?
My Controller are given below
I want to know something new.
public function update(Request $request,$id)
{
$validatedData = $request->validate([
'name' => 'required|max:255',
'title' => 'required',
'details' => 'required',
]);
$data = array();
$data['name'] = $request->name;
$data['title'] = $request->title;
$data['details'] = $request->details;
$data['status'] = $request->status;
$image=$request->photo;
if ($image) {
$image_name = str_random(20);
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/upload/event';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
if ($success) {
$data['photo'] = $image_url;
$img = DB::table('events')->where('id',$id)->first();
$image_path = $img->photo;
$done = unlink($image_path);
$user = DB::table('events')->where('id',$id)->update($data);
if ($user) {
$notification = array(
'messege' => 'Data Updated Successfully',
'alert-type' => 'success'
);
return redirect('admin/event')->with($notification);
}else{
return redirect()->back();
}
}
}else{
return redirect()->back();
}
//return redirect('admin/event')->with($notification);
}
Related
How to update image in this code?
this is the Web.php file
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\auth\DashboardController;
use App\Http\Controllers\auth\ServicesController;
use App\Http\Controllers\Auth\TournamentController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
//Admin Middleware
Route::prefix('admin')->middleware(['auth', 'isAdmin'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'dashboard']);
Route::get('/alltournaments', [TournamentController::class, 'createview']);
Route::get('/create', [TournamentController::class, 'create']);
Route::post('/save-tournament', [TournamentController::class, 'saveTournament']);
Route::get('/edit-tournament/{id}', [TournamentController::class, 'editTournament']);
Route::post('/update-tournament', [TournamentController::class, 'updateTournament']);
Route::get('delete-tournament/{id}', [TournamentController::class, 'deleteTournament']);
Route::get('/manage', [TournamentController::class, 'manage']);
});
//User Middleware
Route::middleware(['auth', 'isUser'])->group(function () {
});
//Public Routes
Route::get('/', [TournamentController::class, 'index']);
Route::get('/tournament/{id}', [TournamentController::class, 'singleTournament']);
And this is controller
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use App\Models\Tournament;
use Illuminate\Support\Facades\File;
class TournamentController extends Controller
{
public function index(){
$data = Tournament::latest()->get();
foreach($data as $d){
if($d->teamsize == 1){
$d->teamsize = "Solo";
}elseif($d->teamsize == 2){
$d->teamsize = "Duo";
}elseif($d->teamsize == 4){
$d->teamsize = "Squad";
}
}
return view('site.home', compact('data'));
}
public function createview(){
$data = Tournament::latest()->get();
foreach($data as $d){
if($d->teamsize == 1){
$d->teamsize = "Solo";
}elseif($d->teamsize == 2){
$d->teamsize = "Duo";
}elseif($d->teamsize == 4){
$d->teamsize = "Squad";
}
}
return view('auth.createmain',compact('data'));
}
//manage view
public function manage(){
$data = Tournament::latest()->get();
return view('auth.manage', compact('data'));
}
//create view
public function create(){
return view('auth.create');
}
//Create
public function saveTournament(Request $request ){
$request->validate([
'tournament_name'=> 'required',
'teamsize'=> 'required',
'check_in_period'=> 'required',
'formate'=> 'required',
'fee'=> 'required',
'prize_pool'=> 'required',
'overview'=> 'required',
]);
$tournament_name =$request->tournament_name;
$teamsize =$request->teamsize;
$check_in_period =$request->check_in_period ;
$formate =$request->formate;
$fee =$request->fee;
$prize_pool =$request->prize_pool;
$overview =$request->overview;
$tournament = new Tournament();
$tournament->title = $tournament_name;
$tournament->check_in_period = $check_in_period;
$tournament->entry_fee = $fee;
$tournament->formate = $formate;
$tournament->overview = $overview;
$tournament->teamsize = $teamsize;
$tournament->prize_pool = $prize_pool;
if($request->hasfile('thumnial'))
{
$file=$request->file('thumnial');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('images/thumnail/',$filename);
$tournament->thumnail=$filename;
}
if($request->hasfile('banner'))
{
$file=$request->file('banner');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('images/banner/',$filename);
$tournament->banner=$filename;
}
$tournament->save();
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Added');
}
//create END
public function editTournament($id){
$data = Tournament:: where('id', '=', $id)->first();
return view('auth.edit', compact('data'));
}
public function updateTournament(Request $request){
$request->validate([
'tournament_name'=> 'required',
'teamsize'=> 'required',
'check_in_period'=> 'required',
'formate'=> 'required',
'fee'=> 'required',
'prize_pool'=> 'required',
'overview'=> 'required',
]);
$id =$request->id;
$tournament_name =$request->tournament_name;
$teamsize =$request->teamsize;
$check_in_period =$request->check_in_period ;
$formate =$request->formate;
$fee =$request->fee;
$prize_pool =$request->prize_pool;
$overview =$request->overview;
Tournament::where('id' , '=', $id)->update([
'title'=> $tournament_name,
'teamsize'=>$teamsize,
'check_in_period'=> $check_in_period,
'formate'=>$formate,
'entry_fee'=>$fee,
'prize_pool'=>$prize_pool,
'overview'=>$overview,
]);
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Edited');
}
//Delete
public function deleteTournament($id){
Tournament::where('id' , '=', $id)->delete();
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Deleted');
}
//User View
public function singleTournament($id){
$data = Tournament:: where('id', '=', $id)->first();
if($data->teamsize == 1){
$data->teamsize = "Solo";
}elseif($data->teamsize == 2){
$data->teamsize = "Duo";
}elseif($data->teamsize == 4){
$data->teamsize = "Squad";
}
return view('site.tournament',compact('data'));
}
}
I need to update image
You can update the image by only inserting this small code:
if ($request->hasfile('banner')) {
$file = $request->file('banner');
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('images/banner'), $filename);
$banner = $filename;
}
Also, below i update your function:
public function updateTournament(Request $request)
{
$request->validate([
'tournament_name' => 'required',
'teamsize' => 'required',
'check_in_period' => 'required',
'formate' => 'required',
'fee' => 'required',
'prize_pool' => 'required',
'overview' => 'required',
]);
$id = $request->id;
$tournament_name = $request->tournament_name;
$teamsize = $request->teamsize;
$check_in_period = $request->check_in_period;
$formate = $request->formate;
$fee = $request->fee;
$prize_pool = $request->prize_pool;
$overview = $request->overview;
if ($request->hasfile('banner')) {
$file = $request->file('banner');
$filename = time() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('images/banner'), $filename);
$banner = $filename;
Tournament::where('id', $id)->update(['banner' => $banner]);
}
Tournament::where('id', $id)->update([
'title' => $tournament_name,
'teamsize' => $teamsize,
'check_in_period' => $check_in_period,
'formate' => $formate,
'entry_fee' => $fee,
'prize_pool' => $prize_pool,
'overview' => $overview,
]);
return redirect()->to('admin/alltournaments')->with('success', 'Tournament Edited');
}
In my Laravel-8, I have this code:
public function add(Request $request){
if( $request->ajax() ){
$rules = array(
'first_name.*' => 'required',
'country.*' => 'required'
);
$error = Validator::make($request->all(),$rules);
if($error->fails()){
return response()->json([
'error' => $error->errors()->all(),
]);
}
$first_name = $request->first_name;
$country = $request->country;
for( $count = 0; $count < count($first_name); $count++ ){
$data = array(
'first_name' => $first_name[$count],
'country' => $country[$count],
);
$insert_data[] = $data;
}
DynamicField::insert($insert_data);
return response()->json([
'success' => 'Data added Successfully',
]);
}
}
This successfully Inserts record.
How do I do the update to this same code?
I mean public function update ...
I am a Laravel beginner and I want to build an API with Laravel 8.
I have posts and images and I want to store and update them.
My store method works and the images are saved in the database and public path in images folders, but in update method I can't save it in folder.
These are my codes:
PostController
public function store(Request $request )
{
$data = $request->all();
//validationg posts and images fields
$validator = Validator::make($data, [
'user_id' => 'required',
'category_id' => 'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time' => 'required',
'tags' => 'nullable|string',
'image' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'خطا در اعتبار سنجی']);
}
//separate tags
$tags = explode(",", $request->tags);
if ($request->hasfile('image')) {
//getting post images from request
$files = $request->file('image');
//saving name and path of images
foreach ($files as $file) {
$imageName = time().rand(1,10000).'.'.$file->extension();
$postTitle = $request->title; //post title for folder name and the images inside it
$imagePath = public_path(). '/images/posts/'.$postTitle;
$file->move($imagePath, $imageName);
$image = new Image;
$image->image = $imageName;
$image->path = $imagePath;
$images[] = $image; // make an array of uploaded images
}
}
$post = Post::create($data);
$post->images()->saveMany($images);//save imageas in image table
$post->tag($tags);//save tags in tags table
return response()->json([
'success' => true,
'message' => 'با موفقیت ثبت گردید ',
'data' => $post
]);
}
public function update(Request $request, $id)
{
$post_failed = Post::find($id);
if (is_null($post_failed)) {
return response()->json('پست مورد نظر یافت نشد ', 404);
}
$data = $request->all();
//validation posts and images fields
$validator = Validator::make($data, [
'user_id' => 'required',
'category_id' => 'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time' => 'required',
'tags' => 'nullable|string',
'image' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'خطا در اعتبار سنجی ']);
}
$tags = explode(",", $request->tags);
if ($request->hasfile('image')) {
$postTitle = $request->title; //post title for folder name and the images inside it
//delete last Images from database for updating images
Image::where('imageable_type', 'App\Models\Post')->where('imageable_id' , $id)->delete();
//delete last images images folder
File::delete(public_path('/images/posts/'.$postTitle));
$files = $request->file('image');
foreach ($files as $file) {
$imageName = time().rand(1,10000).'.'.$file->extension();
$imagePath = public_path(). '/images/posts/'.$postTitle;
$image = new Image();
$image->image = $imageName;
$image->path = $imagePath;
$images[] = $image;
}
}
$post = Post::find($id);
$post->user_id = $data['user_id'];
$post->category_id = $data['category_id'];
$post->title = $data['title'];
$post->body = $data['body'];
$post->study_time = $data['study_time'];
$post->tags = $data['tags'];
$post->save();
$post->images()->saveMany($images);
$post->tag($tags);
return response()->json([
'success' => true,
'message' => 'با موفقیت ویرایش گردید ',
'data' => $post
]);
}
The relation between posts and images is polymorphic one to many and I tested it with postman.
Postman
Database
And the path:
Please, help.
In store() method you saved images on disk by using
$imagePath = public_path(). '/images/posts/'.$postTitle;
$file->move($imagePath, $imageName);
In update() you deleted them
File::delete(public_path('/images/posts/'.$postTitle));
and determined path for new files
$imagePath = public_path(). '/images/posts/'.$postTitle;
but nothing happens after this. In whole update() method there is no code that could do something in storage, so of course nothing appears in folder ;)
So again use $file->move() or Storage facade to save files.
TIP
Also this is bad practice to repeat long code logic like that. It would be better to extract this and share between store/update.
I am a beginner in laravel. I'm trying to submit a post with the option to upload multiple files if the user wants. I keep getting the error "Undefined variable: data." Where did I go wrong?
public function store(Request $request)
{
//validate
$this->validate($request, [
'title' => 'required|min:10',
'body' => 'required|min:20',
'filename' => 'nullable|max:2480',
'filename.*' => 'mimes:jpeg,jpg,png'
]);
//store Image
if($request->file('filename'))
{
foreach($request->file('filename') as $image)
{
$name=time().$image->getClientOriginalName();;
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$post= new Post();
$post->user_id = auth()->user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->filename=json_encode($data);
$post->save();
return back()->withMessage('Post created successfully.');
}
I think that it will be better to declare your array outside the foreach loop.
You can try something like this:
Outside your foreach loop.
$data = array();
Inside your foreach loop, try to populate the array like this:
array_push($data, $name);
public function store(Request $request)
{
//validate
$this->validate($request, [
'title' => 'required|min:10',
'body' => 'required|min:20',
'filename' => 'nullable|max:2480',
'filename.*' => 'mimes:jpeg,jpg,png'
]);
//Initialize an empty array
$data = array();
//store Image
if($request->file('filename'))
{
foreach($request->file('filename') as $image)
{
$name=time().$image->getClientOriginalName();;
$image->move(public_path().'/images/', $name);
//populate array here
array_push($data, $name);
}
}
$post= new Post();
$post->user_id = auth()->user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->filename=json_encode($data);
$post->save();
return back()->withMessage('Post created successfully.');
}
I updated and image is showed after that, but i need to delete the previous image (from folder) after updating with the new one.
//update
public function edit ($id)
{
$user = User::find($id);
// $user = User::where('id', $id)->first();
// $user = DB::table('users')->where('id', $id)->first();
return view('edit', compact('user'));
}
public function postEdit (Request $request) {
request()->validate([
'email' => 'required',
'fullname' => 'required',
'birthday' => 'required',
'address' => 'required|min:10',
]);
$image = $request->image;
// dd($image);
$id = $request->id;
$email = $request->email;
$fullname = $request->fullname;
$address = $request->address;
$birthday = $request->birthday;
$country = $request->country;
$image = $request -> file('image');
$destination = base_path().'/public/img';
$file_name = rand(100,1).date('h-i-s');
$image->move($destination, $file_name.".".$image->getClientOriginalExtension());
$img = $file_name.".".$image->getClientOriginalExtension();
User::where('id',$id)->update([
'image' => $img,
'email' => $email,
'fullname' => $fullname,
'birthday' => $birthday,
'address' => $address,
'country' => $country,
]);
return Redirect::to("dashboard")->withSuccess('Great! You have Successfully edited');
}
You can use File facade to delete a file:
use Illuminate\Support\Facades\File;
$pathToFile = base_path('public/img/'.$user->image);
File::delete($pathToFile);
You should first find the user and determine if he already has an image, sou you can delete it from the storage. Do it like this:
public function postEdit (Request $request) {
request()->validate([
'email' => 'required',
'fullname' => 'required',
'birthday' => 'required',
'address' => 'required|min:10',
]);
$user = User::where('id', $request->id)->first();
if($user->image){ //Check if user has image and delete it from storage
if (Storage::exists($user->image)) {
Storage::delete( $user->image ); //Dont forget to use your real paths. $user->image should be a path to an image.
}
}
$image = $request->image;
$id = $request->id;
$email = $request->email;
$fullname = $request->fullname;
$address = $request->address;
$birthday = $request->birthday;
$country = $request->country;
//Insert new image
$image = $request -> file('image');
$destination = base_path().'/public/img';
$file_name = rand(100,1).date('h-i-s');
$image->move($destination, $file_name.".".$image->getClientOriginalExtension());
$img = $file_name.".".$image->getClientOriginalExtension();
//Now update user
$user->update([
'image' => $img,
'email' => $email,
'fullname' => $fullname,
'birthday' => $birthday,
'address' => $address,
'country' => $country,
]);
return Redirect::to("dashboard")->withSuccess('Great! You have Successfully edited');
}