Can not pass variable to Config::set in laravel elfinder - laravel

I am using laravel 5.5 with backpack as admin panel and i making a project for listing Departments and their Clients and i want to use elfinder to connect to each client folder when i edit the client , So i created a middleware for elfinder to create the client folder and to change the elfinder.dir to that directory the first part of creating dir is done but the problem is in Config::set is not working ,My Code is:
The Middleware :
public function handle($request, Closure $next)
{
$iid = $request->route('client');
if (!Storage::disk('doc')->exists('$iid')){
Storage::disk('doc')->makeDirectory($iid);
}
\Config::set('elfinder.dir', $iid);
return $next($request);
}
The Route:
Route::get('admin/client/{client}/edit', 'Admin\ClientCrudController#edit')->middleware('elfindernew');
The ElfinderController :
public function showConnector()
{
$roots = $this->app->config->get('elfinder.roots', []);
if (empty($roots)) {
$dirs = (array) $this->app['config']->get('elfinder.dir', []);
foreach ($dirs as $dir) {
$roots[] = [
'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
'path' => storage_path('doc')."/".$dir,
'URL' => url($dir), // URL to files (REQUIRED)
'accessControl' => $this->app->config->get('elfinder.access') // filter callback (OPTIONAL)
];
}
I don't Know what is wrong Can someone Help me.....

You have to do it like this:
config(['elfinder.dir', $iid]);

Related

Laravel localization and routes from Jetstream / Fortify

I have this new Laravel project to work on. We would like to make it available in multiple languages.
I started the project with JetStream. Routes for authentication and such are automatically handled by JetStream / Fortify. I then added https://github.com/mcamara/laravel-localization to handle the localization. it works fine for the routes I created myself :
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
], function()
{
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
But how can I set the group, prefix and middleware on the routes handled by Jetstream and Fortify?
[EDIT]
So after some suggestions from #TEFO, I'm trying to add a middleware to handle setting the locale. Added :
Fortify.php :
'path' => '{lang}',
'middleware' => ['web', 'setLang']
new middleware setLang :
class SetLang {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(\Illuminate\Http\Request $request, Closure $next) {
// $lang = 'en';
// $request->attributes->add(['lang' => 'en']);
$request->route()->setParameter('lang', 'en');
// $request->request->set('lang', 'en');
return $next($request);
}
}
Added the middleware to $routeMiddleware.
I'm receiving this error when trying to reach http://mylaravel/en/login :
ErrorException
Missing required parameters for [Route: login] [URI: {lang}/login]. (View: /var/www/resources/views/auth/login.blade.php)
Finally successfully nailed this. I simply disabled routes from Fortify and Jetstream, copied them over and shoved them inside my grouped prefix routes. Still using https://github.com/mcamara/laravel-localization but it should work anyway you want it - make your own system or whatever, as long as you control the routes you're good to go.
In JetstreamServiceProvider :
public function register() {
Jetstream::ignoreRoutes();
}
In FortifyServiceProvider :
public function register() {
Fortify::ignoreRoutes();
}
And copy over routes from Fortify vendor/laravel/fortify/routes/routes.php and Jetstream vendor/laravel/jetstream/routes/livewire.php (I guess adapt to Inertia if you're working with this) over to your web.php file, inside a route group with the prefix you need.
I faced almost the same problem with the expection that i do not use mcamara/laravel-localization at the moment.
Based on the useful discussion above between #JeremyBelolo and #TEFO, the following solution worked for me:
Added 'path' => '{locale}/my-secret-path' to config/fortify.php. As #JeremyBelolo and #ETO discussed, the support for that was recenlty added.
Added my middleware before \Laravel\Jetstream\Http\Middleware\AuthenticateSession::class to the web $middlewareGroups
Where my middleware set the locale app()->setLocale($locale); and the default {locale} url parameter URL::defaults(['locale' => $locale]); before passing the request deeper into the application.
Considering Jetstream I had to apply the same steps as #JeremyBelolo did, exept I didn't copy the jetsream/livewire routes but used the following inside the route group:
require base_path('vendor/laravel/jetstream/routes/livewire.php');
Now I can access {locale}/my-secret-path/login where {locale} is a supported locale for my site.
UPDATE [Fortify config option changed]:
The path fortify config option changed to prefix. Thus in config/fortify.php the following key should be used:
'prefix' => '{locale}/my-secret-path'
I made a new Laravel Project using Jetstream. I wanted to use multi-language support in my project, but when I used Prefix (en/login, de/login) according to languages in url, I was also having a problem with Route. I solved my problem by following these steps. I hope you will be useful too:
1 - I have included the package on this https://github.com/mcamara/laravel-localization in my project. and followed the instructions sequentially.
2 - I made the Route settings in the "rautes\web.php" file as follows.
Route::group(['prefix' => LaravelLocalization::setLocale(),'middleware' => [
'localeSessionRedirect', 'localizationRedirect','localeViewPath' ]], function(){
/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
Route::get('/', function () {return view('welcome');});
Route::middleware(['auth', 'verified'])->get('/dashboard', function () {
return view('back.dashboard');})->name('dashboard');
});
3 - I have included the in app\Http\Middleware\Kernel.php. In middlewareGroups end of web prefix.
protected $middlewareGroups = [
'web' => [....
\Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
\Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
\Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
\Mcamara\LaravelLocalization\Middleware\LocaleCookieRedirect::class,
\Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class,]
4 - Fortify Routes, include prefix in vendor\laravel\fortify\routes.php - Route::group like this:
Route::group(['prefix' => LaravelLocalization::setLocale(),
'middleware' => config('fortify.middleware', ['web'])], function () {
$enableViews = config('fortify.views', true);
.......
5 - Livewire Routes, include prefix in vendor\laravel\jetstream\routes\livewire.php - Route::group like this:
Route::group(['prefix' => LaravelLocalization::setLocale(),
'middleware' =>config('jetstream.middleware', ['web'])], function () {
if (Jetstream::hasTermsAndPrivacyPolicyFeature()) {
Route::get('/terms-of-service', [TermsOfServiceController::class, 'show'])-
>name('terms.show');
Route::get('/privacy-policy', [PrivacyPolicyController::class, 'show'])-
>name('policy.show');}
6 - If you want to separate backend and frontend, you can add in app\Http\Middleware\Kernel.php end of protected $routeMiddleware with prefix like in this https://github.com/mcamara/laravel-localization.
protected $routeMiddleware = [
........
'localize'=> \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
'localeCookieRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleCookieRedirect::class,
'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class,
]
7 - And the happy end...

How to upload an image to the corresponding tenant in Laravel?

First time I'm working with multi-tenant, and I have multiple tenants, the thing is that I don't know how to upload to Storage to the corresponding tenant image.
For example:
Tenant 1:
Upload your company logo
Tenant 2:
Upload your own company logo
I'm currently working with tenant 59138 (storage/app/tenancy/tenants/59138/[here add image folder]
Config Filesystems
'tenancy' => [
'driver' => 'local',
'root' => storage_path('app/tenancy/tenants/'),
],
Controller
public function storeImage(Request $request){
//dd($request->all());
if ($request->file('logo')) {
$fileLogo = $request->file('logo');
$path = Storage::disk('tenancy')->put('public',$fileLogo);
}
}
public function uploadFile(Request $request){
$File = $request->file('data');
//First Parameter is the Folder Name and Second Parameter is the File Object
$stored = \Storage::disk('public')->put("your_folder_name", $File);
$url = tenant_asset($stored);
return response()->json(['success' =>$url], 200);
}

production.ERROR: exception 'ReflectionException' with message 'Class App\Http\Controllers\Api\Builder\SiteController does not exist' in compiled.php

I'm trying to immerge two Laravel 5.2 projects the first one is using Api and the second doesn't. I copied all the controllers, the views and routes to the first project, and in the database i added the other tables using migrations and models but i immerged the user table by adding columns that doesn't exist in the first table, so i have one user for both projects.
I also added all the routes but i want to use the api middleware of the first project on the dashboard page of the second project so i added the controller in the api folder inside a folder named builder and write the route like that :
// Routes.php
Route::group(['namespace' => 'Api', 'prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
// Route::group(['namespace' => 'Api', 'prefix' => 'api/v1'], function () {
Route::get('', 'HomeController#index');
//added for testing builder
Route::get('/dashboard','Builder\SiteController#getDashboard');
And yet i'm getting this error, This is the function that shows the error in compiled.php :
public function signatureParameters($subClass = null)
{
$action = $this->getAction();
if (is_string($action['uses'])) {
list($class, $method) = explode('#', $action['uses']);
$parameters = (new ReflectionMethod($class, $method))->getParameters();
} else {
$parameters = (new ReflectionFunction($action['uses']))->getParameters();
}
return is_null($subClass) ? $parameters : array_filter($parameters, function ($p) use($subClass) {
return $p->getClass() && $p->getClass()->isSubclassOf($subClass);
});
}

How to call function in __constructor using laravel 5?

I am fetching menus from database based on user rights and displaying it to my web page but if i access any url whose access i don't have then too it opens that page.
For this i have created and called access_denied function which redirect user's home page.
I have called access_denied function from constructor of AuthController because AuthController gets loaded on each page.
I have used following code
AuthController
public function __construct()
{
$this->accessDenied();
}
public function accessDenied()
{
$url_segment1 = Request::segment(1);
$url_segment2 = Request::segment(2);
$url_segment = $url_segment1 . '/' . $url_segment2;
$user_data = Auth::user()->toArray();
$dadmin = array_keys($user_data['admin']);
//this is sample of array
// $user_data['admin'] => Array
// (
// [admin/roles] => 1
// )
if (!in_array($url_segment, $dadmin)) {
return redirect('/home');
}
}
But I am getting following error
Non-static method Illuminate\Http\Request::segment() should not be called statically, assuming $this from incompatible context
If i using incorrect process then please suggest me correct way to redirect unauthorised user on home page.
First, you should create a middleware. In a command prompt type:
php artisan make:middleware AccessDenyMiddleware
Then you go to app/Http/Middleware/AccessDenyMiddleware.php and fill in the handle function {your own code}
$url_segment1 = Request::segment(1);
$url_segment2 = Request::segment(2);
$url_segment = $url_segment1 . '/' . $url_segment2;
$user_data = Auth::user()->toArray();
$dadmin = array_keys($user_data['admin']);
//this is sample of array
// $user_data['admin'] => Array
// (
// [admin/roles] => 1
// )
if (!in_array($url_segment, $dadmin)) {
return redirect('/home');
}
But add the following line
return $next($request); // If passed, proceed with the route
Then, in a route, you should type:
Route::get('/yoururlhere', ['middleware' => 'AccessDenyMiddleware', function() { /* Put your work here */ } ]);
There are much better approaches. Like Authorisation if you are using Laravel 5.2
Or maybe change the default Authenticate middleware if you are using Laravel 5
You can use a middleware for thath https://laravel.com/docs/5.2/middleware#introduction.
php artisan make:middleware RoleRouteMiddleware
You should put thath code in the handle method of the middleware "App\Http\Middleware\RoleRouteMiddleware" and use the $request variable instead of the facade Request.
The middleware would filter earch request to your app.
Register a middleware, add it on app/Http/Kernel.php at routeMiddleware array
protected $routeMiddleware = [
....
'alias' => App\Http\Middleware\RoleRouteMiddleware::class,
];
and then use it on specific routes like this:
Route::get('admin/profile', ['middleware' => 'alias', function () {
//your code here
}]);
or in route gruoups:
Route::group(['middleware' => 'alias', function () {
//your filtered routes
}]);

creating a folder once user registred laravel 5

I would like to create a folder inside Storage folder in Laravel 5, once you register and pick your username, a folder with that user will be created for you.
If you created user : john5500 a folder inside Storage will be created with 'john5500' and will belong only to that user.
Mark, see the code below.
This code I use to create a new user in my database.
Information about ManagementCreateRequest $Request can be found via this URL.
Laravel Controller Validation
In short I'm validating my input via Controller Validation in Laravel.
After the validation passes I get all the data from the validation in the variable $Request.
After that I create the user as below. After creating the user I send a redirect to the management page. This page contains an overview of all the users in the database.
public function store(ManagementCreateRequest $Request)
{
// Create user
Management::create($Request->all());
// Return view
return redirect('management')
->with('Success', 'User created.');
}
If I would to create a directory I would do it like this.
public function store(ManagementCreateRequest $Request)
{
// Create user
Management::create($Request->all());
// Create directory
File::MakeDirectory('/path/to/directory' . $Request->username);
// Return view
return redirect('management')
->with('Success', 'User created.');
}
Replace /path/to/directory with the actual path to your storage directory.
For example: Under CentOS my storage directory would be.
/var/www/Site Name/storage
Don't forget to replace 'Site Name' with the name of your Laravel site.
More detailed information about File:makeDirectory can be found via this link:
Laravel Creating Directory
Lravel 5 comes with an excellent filesystem. You could simply do:
Storage::makeDirectory($directory);
See the documentation for more details: http://laravel.com/docs/5.0/filesystem#basic-usage
You can use Laravel File Facade:
File::makeDirectory($path, $mode = 0755, $recursive = false, $force = false);
Ensure storage is writable
public function create(array $data)
{
//return
$user = User::create([
'name' => $data['name'],
'username'=>$data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
\File::makeDirectory(storage_path($data['username']));
return $user;
}

Resources