I'm trying to upload an image, store it on disk and add the path to a JSON file that is stored on the database.
every user got a JSON file with all his images like:
{"images": ["/vendors/57/horse-11.png", "/vendors/57/horse-11.png"]}
That JSON file is stored in the database in the 'images' column.
I'm struggling with this issue for days.. I always get following exception:
Serialization of 'Illuminate\Http\UploadedFile' is not allowed
the error occurs in this part of the code from the processImage function:
$image = Image::make($request->file('image'))
->resize(750, null, function ($constraint) {
$constraint->aspectRatio();
})
->encode('png');
I will guide you through the proces:
first the user uploads an image, code:
https://codeshare.io/jGzQ9
secondly, via the routes.php a controller is called:
public function update(User $user, UserHouse $house, UserHouseRequest $request){
$path = $this->processImage($request, $user->id, $house->id);
$jsonstring = $house->images;
array_push($jsonstring['images'], $path);
$house->images = $jsonstring;
$house->save();
return back();
}
private function processImage($request, $userId, $houseId)
{
$path = null;
$number = rand(1, 99);
if ($request->hasFile('image')) {
$image = Image::make($request->file('image'))
->resize(750, null, function ($constraint) {
$constraint->aspectRatio();
})
->encode('png');
$path = "/users/{$userId}/house-{$houseId}-{$number}.png";
Storage::disk('fileadmin')->put($path, $image->encoded);
}
return $path;
}
There is also some JS code, but I think that that isn't necessary for this problem. If it does, I will add it later.
I'm using Laravel 5.5
stacktrace:
2019-05-28 13:30:49] local.ERROR: Serialization of 'Illuminate\Http\UploadedFile' is not allowed {"userId":57,"email":"info#ho.com","exception":"[object] (Exception(code: 0): Serialization of 'Illuminate\\Http\\UploadedFile' is not allowed at /Users/sg/ah-website/user/laravel/framework/src/Illuminate/Session/Store.php:128)
[stacktrace]
#0 /Users/sg/website/user/laravel/framework/src/Illuminate/Session/Store.php(128): serialize(Array)
#1 /Users/sg/website/user/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(87): Illuminate\\Session\\Store->save()
#2 /Users/sg/website/user/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(218): Illuminate\\Session\\Middleware\\StartSession->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))
#3 /Users/sg/website/user/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(189): Illuminate\\Foundation\\Http\\Kernel->terminateMiddleware(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))
#4 /Users/sg/website/public/index.php(60): Illuminate\\Foundation\\Http\\Kernel->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))
#5 /Users/sg/website/server.php(21): require_once('/Users/sg...')
#6 {main}
"}
config/filesystems.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => env('FILESYSTEM_CLOUD', 's3'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "s3", "rackspace"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_KEY'),
'secret' => env('AWS_SECRET'),
'region' => env('AWS_REGION'),
'bucket' => env('AWS_BUCKET'),
],
'fileadmin' => [
'driver' => 'local',
'root' => public_path(),
'visibility' => 'public',
'url' => config('app.url'),
],
],
];
Related
I'm trying to figure out why Sanctum gives off this error when I try to login my system.
SQLSTATE[08006] [7] connection to server at "10.1.80.217", port 5000 failed: FATAL: SASL authentication failed
These are the files mentioned in the Laravel Sanctum Documentation which I've already checked but I still don't know what is causing this error. I'll also show the my login page and the related files to it. (I'm using Vue 3 as my frontend.)
Any help is appreciated.
Laravel 9.44.0
PHP 8.22
Vue 3
SignIn.vue (submit login)
onSubmit() {
this.errors = {};
this.loading = true;
this.$store.dispatch('sanctum/signIn', this.params())
.then(() => {
this.$router.replace({ path: "/" });
})
.catch((error) => {
this.throwColor("input", "input.username", "text-amber");
this.throwColor("input", "input.password", "text-amber");
this.errors = this.signInErrors(error);
this.loading = false;
});
},
action.js
export function signIn(context, data) {
return api.get('/sanctum/csrf-cookie')
.then(() => {
return api.post('sanctum/signin', {
'username': data.username,
'password': data.password
})
.then(user => {
let userArray = Object.values(user.data);
let key = userArray.join('|');
user.data['key'] = window.btoa(key);
return api.get('/api/domain/core/administration/security/users/' + user.data.id + '/authorizations', {
// params: { id: user.data.id },
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((authorizations) => {
return context.dispatch('credentials', {
user: user.data,
role: authorizations.data[0],
permission: authorizations.data[1]
})
.then(() => { return [user, authorizations]; });
})
});
})
}
.env
APP_NAME=****
APP_ENV=production
APP_KEY=****
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
CHECK_BROWSER=false
DB_CONNECTION=forgestampede
DB_HOST=10.1.80.217
DB_PORT=5000
DB_PORT_READ=5001
DB_DATABASE=forgestampede
DB_USERNAME=****
DB_PASSWORD=****
BROADCAST_DRIVER=pusher
CACHE_DRIVER=redis
CACHE_DRIVERFILESYSTEM_DISK=local
QUEUE_CONNECTION=redis
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_EXPIRE_ON_CLOSE=true
SESSION_ENCRYPT=true
SESSION_DOMAIN=****
SESSION_SECURE_COOKIE=true
SESSION_SAME_SITE=strict
SANCTUM_STATEFUL_DOMAINS=****
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=10.1.80.217
REDIS_PASSWORD=****
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=****
MAIL_PORT=587
MAIL_USERNAME=****
MAIL_PASSWORD=****
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=****
MAIL_FROM_NAME="${APP_NAME}"
SFTP_HOST=10.1.80.217
SFTP_USERNAME=****
SFTP_PASSWORD=****
SFTP_PORT=2229
SFTP_ROOT=/uploads
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=****
PUSHER_APP_KEY=****
PUSHER_APP_SECRET=****
PUSHER_APP_CLUSTER=mt1
PUSHER_HOST=10.1.80.217
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
Database.php
'forgestampede' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'read' => [
[
'host' => env('DB_HOST'),
'port' => env('DB_PORT_READ'),
],
// [
// 'host' => env('DB_HOST'),
// 'port' => env('DB_PORT'),
// ]
],
'write' => [
[
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
]
],
'sticky' => true,
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'core',
'sslmode' => 'prefer',
],
Sanctum.php
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort()
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. If this value is null, personal access tokens do
| not expire. This won't tweak the lifetime of first-party sessions.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
],
];
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'validate.browser' => \App\Http\Middleware\CheckBrowser::class,
'rbac' => \App\Http\Middleware\CheckPermission::class,
];
}
cors.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
bootstrap.js
window._ = require('lodash');
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: process.env.MIX_PUSHER_APP_KEY,
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
// forceTLS: true
// });
session.php
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE'),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT'),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE'),
];
Make sure you have correct DB connection information in your .env file. It is probably wrong credentials. Check if everything is correct and case sensitive here :
DB_CONNECTION=forgestampede
DB_HOST=10.1.80.217
DB_PORT=5000
DB_PORT_READ=5001
DB_DATABASE=forgestampede
DB_USERNAME=****
DB_PASSWORD=****
It also may be related to the wrong Port. Seems like you are using local app with distant database. Make sure you are not trying to access a production Database.
I am currently writing an application that speaks to an API thorugh an axios post req. in order to receive a response.
I have a .vue component, whose content is a form with given specs.
I installed CORS through the composer, set up my cors.php and added everything neccessary in my kernel.php.
My Vue is stored in a .blade. php view.
Everytime, when I try to send the data, I get this error message by cors:
'http://myurl//' from
origin 'http://api.laragon:8090' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: It
does not have HTTP ok status.
The data is send through post as mentioned with a form, that runs this method when submit button is clicked:
formSubmit(e) {
const url="x";
e.preventDefault();
let currentObj = this;
this.axios
.post(url, {
age: this.age,
claimantType: this.claimantType,
// zipcode: this.zipcode,
mcMax: 3,
icdCount: 1,
iCDCountInitialIllnesses: 0, //fix:0
uniqueVisitedDoctorsCount: 1, //fix:1
daysBetweenAccidentAndAC: 20, //fix:20
daysInHospital: 0, //fix:0
s13_4_only: 0 //fix:0 => 1, if only! selected
})
.then(function(response) {
currentObj.output = response.data;
})
.catch(function(error) {
currentObj.output = error;
console.log(error);
});
}
/config/app.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
Barryvdh\Cors\ServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Arr' => Illuminate\Support\Arr::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'Str' => Illuminate\Support\Str::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
],
];
/config/cors.php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
];
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Barryvdh\Cors\HandleCors::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* #var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
web.php
Route::get('/', function(){
return view('start');
});
Route::get('/home', function () {
return view('home');
});
used this tut for cors set-up:
https://github.com/barryvdh/laravel-cors
check the message Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
This mean your option method is not responding 2xx status code. check if you dont have problems in the configuration of your API, and check if you have maintenance mode on the Laravel API.
Use php artisan up to disable maintenance mode.
you dont have CORS policy.
install this "composer require spatie/laravel-cors" then put this middleware and the error will gone
// app/Http/Kernel.php
protected $middleware = [
...
\Spatie\Cors\Cors::class
];
Although I did not get the 404 error (which may be your first issue), i got the same "Response preflight ... status not ok" error.
In my case, the API Controller that handles the request was validating the request information. It checked for required informations using the validate function. As I did not post the required field in my request, the validation failed and the server did not respond with a HTTP status ok.
So you may check your API controller.
The only solutions that comes to mind is putting the middleware Barry on top of the middlewares on the Kernel file...
Havent tried Spatie pack yet though, tell me if you manage...
also try to manage preflight... like two responses
if ($request->isMethod("OPTIONS")) {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
// return $response('');
}
//$request->headers->set('Accept', 'application/json');
$response = $next($request);
I'm trying to store a file via AJAX to public folder in laravel, however when I submit the form I get the following message:
" message: "Impossible to create the root directory \"C:\xampp\htdocs\Restaurante1\storage\app\C:/xampp/htdocs/Restaurante1/public/img\".", exception: "League\Flysystem\Exception", file: "C:\xampp\htdocs\Restaurante1\vendor\league\flysystem\src\Adapter\Local.php"
I'm trying to store the file into the following folder inside public directory: public > img >uploads
This is my JQuery code:
console.log('new slider button clicked');
var formData = new FormData();
formData.append('title', $('#sliders_title').val());
formData.append('body', $('#sliders_body').val());
formData.append('isVisible', $('#sliders_isVisible').is(':checked') ? 1 : 0);
formData.append('image', $('#sliders_image').prop('files')[0]);
$.ajax({
async: true,
url: '/sliders',
type: 'POST',
data: formData,
dataType: 'JSON',
processData: false,
contentType: false,
success: function (data) {
$('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(){
$('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My controller method:
public function store(StoreSlider $request)
{
$uploadFile = $request->file('image');
//generate random filename and append original extension (eg: asddasada.jpg, asddasada.png)
$filename = str_random(6).'.'.$uploadFile->extension();
// storing path (Change it to your desired path in public folder)
$path = 'img/uploads/';
// Move file to public filder
$uploadFile->storeAs(public_path($path), $filename);
$slider = new Slider();
$slider->title = $request->title;
$slider->body = $request->body;
$slider->image = $path.'/'.$filename; // So that you can access image by url($slider->image);
$slider->isVisible = $request->isVisible;
$slider->save();
return response()->json([
'success' => 'Diapositiva guardada correctamente',
'slider' => $slider,
]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
EDIT: This is my config/filesystems
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => env('FILESYSTEM_CLOUD', 's3'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "sftp", "s3", "rackspace"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
],
],
];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My answer might not be relevant this very question but should in case someone encounters the same problem I think might be of help. I encountered the same problem and I "putFileAs" which worked the same way as "storeAs" like so $path = Storage::putFileAs('public/users_upload/'.$user->username, $File_to_be_moved, $file_name_to_store_as); First parameter is for the path to your directory... You can check the laravel documentation for more info here
in your FileSystem, you need to create the driver disk.
'uploads' => [
'driver' => 'local',
'root' => public_path('img/uploads'),
'url' => '/img/uploads',
'visibility' => 'public',
],
and you can call in your controller storage
$uploadFile->storeAs('/', $filename, 'uploads');
I needed to use a dynamic callback url for socialite so I added the url() function to my services.php file it worked fine(and its still working on my live server) But when tried to start the project locally I get the following error. When I remove the url() method everything works fine please help.
PHP Fatal error: Uncaught ReflectionException: Class log does not exist in /home/fenn/projects/jokwit/vendor/laravel/framework/src/Illuminate/Container/Container.php:734
Stack trace:
#0 /home/fenn/projects/jokwit/vendor/laravel/framework/src/Illuminate/Container/Container.php(734): ReflectionClass->__construct('log')
#1 /home/fenn/projects/jokwit/vendor/laravel/framework/src/Illuminate/Container/Container.php(629): Illuminate\Container\Container->build('log', Array)
#2 /home/fenn/projects/jokwit/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(697): Illuminate\Container\Container->make('log', Array)
#3 /home/fenn/projects/jokwit/vendor/laravel/framework/src/Illuminate/Container/Container.php(849): Illuminate\Foundation\Application->make('log')
#4 /home/fenn/projects/jokwit/vendor/laravel/framework/src/Illuminate/Container/Container.php(804): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#5 /home/fenn/projects/jokwit/vendor/laravel/framework/src/Illuminate/Container/Container.php(7 in /home/fenn/projects/jokwit/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 734
Here is my services.php file
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, Mandrill, and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'mandrill' => [
'secret' => env('MANDRILL_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'us-east-1',
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
'facebook' => [
'client_id' => '1700935300171729',
'client_secret' => 'XXXXXXXXXXXXXXXXXXX',
'redirect' => url('/facebook/callback'),
],
'google' => [
'client_id' => 'XXXXXXXXXXXXXXXXXXXXXXXX',
'client_secret' => 'XXXXXXXXXXXXXXXXXXXXXXXX',
'redirect' => url('google/callback'),
],
];
In services.php file
...
'redirect' => 'google/callback',
...
Next create service provider for example ConfigServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ConfigServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
\Config::set("services.google.redirect", url(\Config::get('services')['google']['redirect']));
}
}
now should work fine
It doesn't work because in production Laravel cached all configuration files and using this cache. In development environment Laravel didn't create cache.
You can check it by commenting url() in config and then running php artisan config:cache command. Uncomment url() part and you'll see error is disappeared.
The best you can do here is to not use Laravel or manually defined functions in config files and find another solution for your problem.
I am quite new in laravel/lumen framework. I am using lumen 5.2 to build a restful API. For authentication, I am trying to implement JWT authentication I am following this https://laravelista.com/json-web-token-authentication-for-lumen article for guidance. I install and configure this https://github.com/tymondesigns/jwt-auth
packages. It works fine and gives me following error if i do not provide a token {"error":"token_not_provided"} .But when i am trying to generate a token by passing email and password in a post request then it fails and give following error.
in AuthManager.php line 137
at Application->Laravel\Lumen\Concerns\{closure}('8', 'Undefined index: provider', 'D:\xamp\htdocs\lumen_api\vendor\illuminate\auth\AuthManager.php', '137', array('name' => 'api', 'config' => array('driver' => 'token'))) in AuthManager.php line 137
at AuthManager->createTokenDriver('api', array('driver' => 'token')) in AuthManager.php line 77
at AuthManager->resolve('api') in AuthManager.php line 57
at AuthManager->guard() in AuthManager.php line 244
at AuthManager->__call('once', array(array('email' => 'testadmin#gmail.com', 'password' => 'password'))) in IlluminateAuthAdapter.php line 39
at AuthManager->once(array('email' => 'testadmin#gmail.com', 'password' => 'password')) in IlluminateAuthAdapter.php line 39
at IlluminateAuthAdapter->byCredentials(array('email' => 'testadmin#gmail.com', 'password' => 'password')) in JWTAuth.php line 108
at JWTAuth->attempt(array('email' => 'testadmin#gmail.com', 'password' => 'password')) in Facade.php line 216
at Facade::__callStatic('attempt', array(array('email' => 'testadmin#gmail.com', 'password' => 'password'))) in AuthController.php line 45
at JWTAuth::attempt(array('email' => 'testadmin#gmail.com', 'password' => 'password')) in AuthController.php line 45
at AuthController->postLogin(object(Request))
at call_user_func_array(array(object(AuthController), 'postLogin'), array(object(Request))) in Container.php line 507
at Container->call(array(object(AuthController), 'postLogin'), array()) in RoutesRequests.php line 581
at Application->callControllerCallable(array(object(AuthController), 'postLogin'), array()) in RoutesRequests.php line 548
at Application->callLumenController(object(AuthController), 'postLogin', array(true, array('uses' => 'App\Http\Controllers\AuthController#postLogin'), array())) in RoutesRequests.php line 521
at Application->callControllerAction(array(true, array('uses' => 'App\Http\Controllers\AuthController#postLogin'), array())) in RoutesRequests.php line 489
at Application->callActionOnArrayBasedRoute(array(true, array('uses' => 'App\Http\Controllers\AuthController#postLogin'), array())) in RoutesRequests.php line 474
at Application->handleFoundRoute(array(true, array('uses' => 'App\Http\Controllers\AuthController#postLogin'), array())) in RoutesRequests.php line 376
at Application->Laravel\Lumen\Concerns\{closure}() in RoutesRequests.php line 624
at Application->sendThroughPipeline(array(), object(Closure)) in RoutesRequests.php line 382
at Application->dispatch(object(Request)) in RoutesRequests.php line 327
at Application->run(object(Request)) in index.php line 29
Here is my Authcontroller code:
namespace App\Http\Controllers;
use Illuminate\Http\Exception\HttpResponseException;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\Request;
use Illuminate\Http\Response as IlluminateResponse;
class AuthController extends Controller{
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
try
{
$this->validate($request, [
'email' => 'required|email|max:255', 'password' => 'required',
]);
}
catch (HttpResponseException $e)
{
return response()->json([
'error' => [
'message' => 'Invalid auth',
'status_code' => IlluminateResponse::HTTP_BAD_REQUEST
]],
IlluminateResponse::HTTP_BAD_REQUEST,
$headers = []
);
}
$credentials = $this->getCredentials($request);
try
{
// attempt to verify the credentials and create a token for the user
//$customClaims = ['email' => 'rahul.rksaini#gmail.com', 'password' => 'password'];
if ( ! $token = JWTAuth::attempt($credentials))
{
return response()->json(['error' => 'invalid_credentials'], 401);
}
}
catch (JWTException $e)
{
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getCredentials(Request $request)
{
return $request->only('email', 'password');
}
}
===================================
my .env file content
APP_ENV=local
APP_DEBUG=true
APP_KEY=swe09w8w7r6t5y4uio321!#wsceszwer
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=api_db
DB_USERNAME=root
DB_PASSWORD=
CACHE_DRIVER=memcached
QUEUE_DRIVER=sync
JWT_SECRET=cv4d4se065r1td0sw6e8d9za9q102jhes060a3wer
AUTH_DRIVER=jwt
AUTH_MODEL=\App\Models\User
AUTH_TABLE=users
I google it a lot but not get any solution yet. Please help me to figure it out.
thank in advance.
Here is the directory structure of vendor folder
![][vender folder]
You may write your own auth configuration file in config/auth.php (if it doesn't exist, you may create on yourself). See configuration here.
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'api'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
| NOTE: "token" driver is not supported in JWT Auth
|
*/
'guards' => [
'api' => [
'driver' => 'session',
'provider' => 'users'
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
// We should get model name from JWT configuration
'model' => app('config')->get('jwt.user'),
],
],
];
Fortunately, I create a simple JWT Authentication implemented in Lumen here.