How can I update image in Laravel - laravel

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

Related

How to use livewire pagination with public properties?

I'm facing a weird problem that only accurs when I use pagination with livewire components,
this is the error:
BadMethodCallException
Method Illuminate\Support\Collection::items does not exist.
I know what this errors means, the problem is why it only accurs when I change page in pagination:
this is my Component:
<?php
namespace App\Http\Livewire\Admin;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use App\Models\Product;
use App\Models\Category;
use File;
use GlobalsHelper;
class Products extends Component
{
use WithPagination, WithFileUploads;
public $products;
public $subcategories;
// Form
public $name;
public $description;
public $price;
public $quantity;
public $category_id = null;
public $sub_category_id = null;
public $image;
public $selected = [];
public $query = '';
public $filter_by_category = '';
protected $paginationTheme = 'bootstrap';
public function render()
{
$pagination = $this->products;
$this->products = collect($this->products->items());
return view('livewire.admin.products', [
'categories' => Category::all(),
'subcategories' => $this->subcategories,
'products' => $this->products,
'pagination' => $pagination
]);
}
// public function render()
// {
// return view('livewire.admin.products', [
// 'categories' => Category::all(),
// 'subcategories' => $this->subcategories,
// 'products' => $this->products,
// ]);
// }
public function mount()
{
$this->getSubcategories();
$this->index();
}
public function getSubcategories()
{
$this->subcategories = [];
if ( !$this->category_id )
{
$this->category_id = (Category::first()) ? Category::first()->id : null;
}
$category = Category::find($this->category_id);
if ( !$category )
{
return null;
}
$this->subcategories = $category->children;
$this->sub_category_id = ($this->subcategories->first()) ? $this->subcategories->first()->id : null;
}
public function store()
{
$fields = $this->validate([
'name' => ['required', 'string', 'min:5', 'max:250'],
'description' => ['string', 'max:250'],
'price' => ['required', 'numeric', 'min:1'],
'quantity' => ['required', 'numeric', 'min:1'],
'category_id' => ['nullable'],
'sub_category_id' => ['nullable'],
]);
$fields['user_id'] = GlobalsHelper::auth()->id;
$product = Product::create($fields);
if ( !$product )
{
session()->flash('error', __('messages.error_create'));
return;
}
// upload image
$this->storeImage($product);
$this->resetFields();
session()->flash('success', __('messages.success_create'));
}
public function search()
{
$results = Product::where('name', 'LIKE', '%'.$this->query.'%')
->orderBy('id', 'desc')->paginate(5);
$this->products = $results;
}
public function index()
{
$this->products = Product::orderBy('id', 'desc')->paginate(5);
}
public function filterByCategory()
{
$results = Product::where('category_id', '=', $this->filter_by_category)
->orderBy('id', 'desc')->paginate(5);
$this->products = $results;
}
// private
private function resetFields()
{
$this->name = null;
$this->description = null;
$this->price = 0;
$this->quantity = 1;
$this->image = null;
$this->filename = '...';
}
private function storeImage($product)
{
$this->validate([
'image' => ['nullable', 'image', 'max:1024'],
]);
if ( $this->image )
{
// Delete old image if exists
if ( $product->image )
{
File::delete([$product->image->fullpath]);
}
$filename = sha1( uniqid('', true) );
$ext = $this->image->getClientOriginalExtension();
$fullpath = $this->image->store(GlobalsHelper::PRODUCTS_UPLOADS_DIR.'/'.$product->id, 'public');
$product->update([
'image' => [
'name' => basename($fullpath),
'type' => $ext,
'fullpath' => GlobalsHelper::STORAGE_DIR.$fullpath,
'url' => asset(GlobalsHelper::STORAGE_DIR.$fullpath)
]
]);
}
}
}
The idea is that I want to achieve search, store, update, delete, filter operations in same compoenent like in laravel controller, I found solutions online, but only 50% of what I need to achieve.
I have been wasting a lot of time trying to figure this out.
If any one would help me, I will be much appreciated.
At first glance without seeing the view, you are getting the $produts via the mount() method, this will only run ONCE when the livewire component is first rendered. From the docs:
mount() is only ever called when the component is first mounted and will not be called again even when the component is refreshed or rerendered.

Image Update Problem Using Laravel Query Builder

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

Laravel - Call to undefined method App\\User::getAvatarUrlAttribute()

I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\User;
use App\Activity;
use Avatar;
use Storage;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Mail;
use Audit;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class ApiController extends Controller
{
public $successStatus = 200;
public function __construct() {
}
protected function guard()
{
return Auth::guard();
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()->email
], 200);
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|string|email|max:255|unique:users',
// 'phone' => 'required',
// 'password' => 'required',
'password' => 'required|string|min:6',
// 'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$input = $request->all();
// code for check email / username / phone exist or not
if(isset($input['email'])){
$alreadyExist = User::where(function ($query) use ($input) {
$query->where('email', '=', $input['email']);
})->get();
}
if (count($alreadyExist->toArray()) > 0) {
return $this->returnResponse(false, ['error' => 'Email Already Exist'], 1, 'User Data Already Exist');
}
// code for register user
$user = new User();
$user->name = $input['name'];
$user->email = $input['email'];
$user->password = bcrypt($input['password']);
$user->save();
$mainData = array();
$mainData['to'] = $user->toArray()[0]['email'];
$mainData['from'] = "support#tsllimited.com";
$mainData['subject'] = "Successful Signup";
$mainData['content'] = "Your signup was successful, you can login with the credentials.";
$this->mailSend($mainData);
Activity::create([
'user_id' => $user->id,
'owner_id' => $user->client_id,
'type' => "User Registration",
'title' => "Successful Signup of User",
'state' => 2,
'created_at'=> date('Y-m-d H:i:s')
]);
$success = array();
$success['user_id'] = $user->id;
$success['user']=$user;
return $this->returnResponse(true, $success, 0, 'User registered successfully');
}
public function login(Request $request) {
$authenticated = false;
$validator = Validator::make($request->all(), [
'email' => 'required|string|email',
'password' => 'required|string',
'remember' => 'boolean'
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
I stalled and configured Laravel Passport and also Spatie. I have checked the code and don't know what the error really is. When I test the resgister Post Request on the POSTMAN, I got the error shown below:
See the POSTMAN preview side:
What could have caused the error and how do I resolve it?
You do not have the column avatar on your users table.
Maybe you did not use the trait you need in your User class
class User extends Authenticatable {
use HasAvatar;
// ...
}
I eventually solved the problem myself. The issue is that, I forgot to add:
public function getAvatarUrlAttribute()
{
return Storage::url('avatars/'.$this->id.'/'.$this->avatar);
}
to User Model.
Thanks

Upload image in public folder

I am trying to insert image in database using laravel 5.4. It works. But when I search that directory then it does not appear there. I also want to validate only images should be upload and size.
Thanks for advance.
My Controller function is here
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Hash;
use App\User;
class regController extends Controller
{
public function create(Request $request)
{
$this-> validate(request(),[
'name' => 'required',
'email'=> 'required',
'type' => 'required',
'image' => 'required',
'password' => 'required|confirmed|min:6',
]);
$request['password'] = bcrypt($request -> password);
$User = new User($request->input()) ;
if($file = $request->hasFile('image')) {
$file = $request->file('image') ;
$fileName = $file->getClientOriginalName() ;
return Storages::putFile('public/images',$request->file('image'));
$destinationPath = public_path().'images/' ;
$file->move($destinationPath,$fileName);
$User->image = $fileName ;
}
$user =
User::create(request(['name','email','type','image','password']));
return redirect('login');
}
try this :
// Validation
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,bmp,png|max:10240' // size in kelobytes this equals 10 mb
]);
$User = new User() ;
$User->password = bcrypt($request->password);
$User->name = $request->name;
$User->type = $request->type;
$User->email = $request->email;
$filename = $this->getFileName($request->image);
$request->image->move(base_path('public/images'), $filename);
$User->image = $fileName;
$$User->save();
return back()->with('success','Image Upload successful');
I just forgot to show you how to implement getFileName function to generate a unique filename sorry about that, in your controller you can define it as protected method like so:
protected function getFileName($file)
{
return str_random(32) . '.' . $file->extension();
}
I think you are tryin to do smth like this:
public function fileUpload(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$input['imagename'] = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $input['imagename']);
$this->postImage->add($input);
return back()->with('success','Image Upload successful');
}

laravel 5.2 - store multiple value with sum

I have a 2 table user and reports
Report model
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
User model
public function reports() {
return $this->hasMany('App\Report', 'author_id');
}
In User model there is a column called "sum_sales"
In Report model there is a column called "total"
Ho can I pass the sum(total) from my Report model to 'sum_total' inside my User model?
My report controller
public function store(Request $request)
{
$this->validate($request, ['title' => 'required',
'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
'image_1' => 'required|mimes:png,jpeg',
'products' => 'required',
'total' => 'required',
'time' => 'required|min:2',
'location' => 'required',
'sub_location' => 'required',
]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$image = $request->file('image_1');
$destinationPath = 'uploads/reports';
$ext = $image->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$ext;
$report->image_1 = $image->move($destinationPath, $fileName);
$field_total = $request->input('total');
$sum_total = $report->sum('total');
$totalSum = $field_total + $sum_total;
$report->author_id->sum_sales = $totalSum;
$report->save();
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
With this the browser say:
Indirect modification of overloaded property App\Report::$author_id has no effect
How can I figure out?
solved by Giedrius Kiršys
public function store(Request $request)
{
$this->validate($request, ['title' => 'required',
'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
'image_1' => 'required|mimes:png,jpeg',
'products' => 'required',
'total' => 'required',
'time' => 'required|min:2',
'location' => 'required',
'sub_location' => 'required',
]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$image = $request->file('image_1');
$destinationPath = 'uploads/reports';
$ext = $image->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$ext;
$report->image_1 = $image->move($destinationPath, $fileName);
$report->save();
$sumUserTotal = User::find($user)->reports->sum('total');
Auth::user()->update(['sum_sales' => $sumUserTotal]);
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}

Resources