in laravel Upload image in two different folder at same time - laravel

This Code save image in only one "folder-one". I want to upload the
image at the same time in two different folders, now it saving in folder-one
example
"folder-one"
and
"folder-two"
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Mail;
use Illuminate\Auth\Events\Registered;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
}
protected function create(array $data)
{
$photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
$data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);
return user::create([
'photo_jpeg' => $photo_jpeg,
]);
}

Use method copy() to make a copy of the file at the new destination.
$request->file('photo')->move($destination_path, $file_name); //original
copy($destination_path.$file_name, $new_path.$file_name); //backup

You can't run move() twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.
You must copy the file:
$uploadPath = public_path('folder-one/');
$file = $data['photo_jpeg'];
$photo_jpeg= time() . '.' .$file->getClientOriginalExtension();
$file->move($uploadPath,$photo_jpeg);
\File::copy($uploadPath.$photo_jpeg,public_path('folder-two/').$photo_jpeg);

Related

I can not delete medialibrary files from storage in boot of model?

In laravel 8 app I with spatie/laravel-medialibrary 9 I want to delete file from storage when I delete parent
model with boot method, like
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\Rule;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class Photo extends Model implements HasMedia
{
use HasFactory;
use InteractsWithMedia;
protected $table = 'photos';
protected static function boot()
{
parent::boot();
static::deleting(function ($photo) {
\Log::info( ' -1 INSIDEstatic::deleting(::' );
foreach ($photo->getMedia('photo') as $mediaImage) {
\Log::info( varDump($mediaImage->getPath(), ' -1 $mediaImage->getPath()::') );
if (File::exists($mediaImage->getPath())) {
\Log::info( varDump($mediaImage->getPath(), ' -1 $mediaImage->getPath()::') );
Storage::delete($mediaImage);
}
}
});
}
But file is not deleted and checking logs I see message
-1 INSIDEstatic::deleting(:
, but not messages inside of
foreach ($photo->getMedia('photo') as $mediaImage) {
loop. Why so ? I expected
static::deleting(function
is triggered BEFORE rmodel is delete in contoller method :
try {
DB::beginTransaction();
$photo->delete();
DB::commit();
How to make delete these files ?
Thanks!

If logged with jwt-auth looks in controller Auth::user() is empty

In my Laravel 5.8/vuejs 2.6 app I use
"tymon/jwt-auth": "^1.0.0",
and my app/Http/Controllers/AuthController.php has method:
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if ($token = $this->guard('api')->attempt($credentials)) {
return $this->respondWithToken($token);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
and I keep token on client side. It works but I want to add more checks on the server's side, when I save data and to make in control's method :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Settings;
use App\Http\Traits\funcsTrait;
use App\Forum;
use App\ForumCategory;
use App\ForumThread;
use App\ForumPost;
use Illuminate\Routing\Controller as BaseController;
use App\User;
use App\library\CheckValueType;
use App\Http\Requests\ForumThreadRequest;
use JavaScript;
class ForumController extends BaseController
{
use funcsTrait;
public function __construct()
{
$this->middleware('auth');
}
public function add_new_thread(ForumThreadRequest $request)
{
$loggedUser = Auth::user();
if ( empty($loggedUser->id) ) {
return response()->json(['error_code'=> 1, 'message'=> "You must be logged!", 'forumThreadRow'=>null],HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
}
try {
But even if I have logged into the system it looks like that in add_new_thread method $loggedUser is empty.
Have I to make some additive actions in login method of AuthController.php or in which way ?
As I use api guard decision is to use :
$user = Auth::guard('api')->user();
This is a late answer, but maybe could help someone.
I had the same issue and it was fixed by adding $table property to the user model User.php
/**
* Specify table name otherwise Auth::user() will return null
*
* #var string
*/
protected $table = 'users';
see here

How to store an image in two different folders in Laravel

The code below stores the image in only one folder. I would like to store the image in two different folders (Folder-A and Folder-B)
Here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Service;
class ServiceController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
$input['image'] = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('Folder-A/'), $input['image']);
Service::create($input);
return back()->with('success', 'CREATED SUCCESSFULLY.');
}
}
You can't run move() twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.
You must copy the file:
$uploadPath = public_path('folder-one/');
$file = $request->file('image');
$photo_jpeg= time() . '.' .$file->getClientOriginalExtension();
$file->move($uploadPath,$photo_jpeg);
\File::copy($uploadPath.$photo_jpeg,public_path('folder-two/').$photo_jpeg);

Laravel file upload not working, and have no idea why

MODEL:
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class product extends Model
{
public function create(Request $request) {
$file = $request->file('photo');
if ( $request->hasFile('photo') && $request->file('photo')->isValid() )
{
$extension = $file->extension();
$name = 'bjdsakbhdebkhdabhkedbhe'.$extension;
$path = $file->storeAs('public/images',$name);
}
else {
return 'error';
}
product::create([
'photo' => $path,
]);
}
protected $fillable = ['name', 'price', 'roast', 'origin', 'photo', 'stock'];
}
CONTROLLER
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\product;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
class adminController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function create(Request $request) {
ini_set('max_execution_time', 300);
$validatedData = $request->validate([
'photo' => 'required|file|image'
]);
$new = new product;
$new->create($request);
}
}
I am trying to upload a file image. I have reworked the above code several times and an error is thrown. Absolutely NO idea why the file is not uploading. It is not a server error. File size and time allowed have been adjusted.
Why are you calling product::create inside your create method in product class? This causes an infinite recursion.

how to define multidimentional array globally in laravel controller?

I want to define multidimentional array in laravel controller globally.
I am defining it like this
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Communication_link;
use App\Contact;
use DateTime;
use App\Resource_status;
use App\Inquiry;
use App\Contact_communication;
use App\Pincode;
use App\City;
use App\User;
class createInquiryController extends Controller
{
public $response;
$map = array(
array("contact","id"),
array("communication_link", "id"),
array("contact_communication","id")
);
public function contact_select(Request $request){
return $map;
}
}
but this is throwing a error "undefined map".
Define it and assign data in constructor:
protected $map;
public function __construct()
{
$this->map = array(
array("contact","id"),
array("communication_link", "id"),
array("contact_communication","id")
);
}
Then you'll have access to this variable from any method in this controller:
public function index()
{
$data = $this->map;
}

Resources