When using Intervention\Image in laravel on lambda
The following error has occurred.
By the way, it works in the local environment.
I have to add gd.
[2021-08-17 10:37:18] DEV.ERROR: GD Library extension not available with this PHP installation.
{"exception":"[object] (Intervention\Image\Exception\NotSupportedException(code: 0):
GD Library extension not available with this PHP installation.
at /var/task/vendor/intervention/image/src/Intervention/Image/Gd/Driver.php:19)
What I looked up
https://bref.sh/docs/environment/php.html#extensions
https://github.com/brefphp/extra-php-extensions
Deployment method
We are deploying to lambda using the sls command.
sls deploy --stage dev
Based on the investigation, the following is implemented
composer require bref/extra-php-extensions
Added below
serverless.yml
plugins:
- ./vendor/bref/bref
- ./vendor/bref/extra-php-extensions #add
functions:
# This function runs the Laravel website/API
web:
image:
name: laravel
events:
- httpApi: '*'
# This function lets us run artisan commands in Lambda
artisan:
handler: artisan
timeout: 120 # in seconds
layers:
- ${bref:layer.php-80}
- ${bref:layer.console}
- ${bref-extra:gd-php-80} #add
Even if the above settings are added and deployed, they are not updated. .. why?
enviroment
Laravel Framework 8.33.1
PHP 7.4.3
bref
serverless
I'm sorry if English is strange.
Put the layers into web "tag".
plugins:
- ./vendor/bref/bref
- ./vendor/bref/extra-php-extensions #add
functions:
# This function runs the Laravel website/API
web:
image:
name: laravel
layers:
- ${bref-extra:gd-php-80} #add
events:
- httpApi: '*'
# This function lets us run artisan commands in Lambda
artisan:
handler: artisan
timeout: 120 # in seconds
layers:
- ${bref:layer.php-80}
- ${bref:layer.console}
Then add the folder php/conf.d inside put a file with extension .ini. For example php.ini. In it just put:
extension=gd
I'm using laravel 8 and bref to deploy it on lambda. After making a cron job function to send email. When I deploy it, there's a problem with the facade
{
"errorType": "RuntimeException",
"errorMessage": "A facade root has not been set.",
"stackTrace": [
"#0 /var/task/app/functions/sendTestMail.php(11): Illuminate\\Support\\Facades\\Facade::__callStatic()",
"#1 /var/task/vendor/bref/bref/src/Runtime/Invoker.php(34): Bref\\Runtime\\FileHandlerLocator->App\\Functions\\{closure}()",
"#2 /var/task/vendor/bref/bref/src/Runtime/LambdaRuntime.php(102): Bref\\Runtime\\Invoker->invoke()",
"#3 /opt/bref/bootstrap.php(43): Bref\\Runtime\\LambdaRuntime->processNextEvent()",
"#4 {main}"
]
}
here is my directory structure and the function:
sendTestMail.php
serverless.yml:
service: test
provider:
name: aws
# The AWS region in which to deploy (us-east-1 is the default)
region: ap-southeast-1
# The stage of the application, e.g. dev, production, staging… ('dev' is the default)
stage: dev
runtime: provided.al2
package:
# Directories to exclude from deployment
exclude:
- node_modules/**
- public/storage
- resources/assets/**
- storage/**
- tests/**
functions:
# This function runs the Laravel website/API
web:
handler: public/index.php
timeout: 28 # in seconds (API Gateway has a timeout of 29 seconds)
layers:
- ${bref:layer.php-80-fpm}
events:
- httpApi: "*"
# This function lets us run artisan commands in Lambda
artisan:
handler: artisan
timeout: 120 # in seconds
layers:
- ${bref:layer.php-80} # PHP
- ${bref:layer.console} # The "console" layer
cron:
handler: app/functions/sendTestMail.php
layers:
- ${bref:layer.php-80}
events:
- schedule: rate(5 minutes)
plugins:
# We need to include the Bref plugin
- ./vendor/bref/bref
Anyone know how to resolve this issue? And btw, how can I test a handler function on my local machine before deploying? Thank you
I believe this is due to the issue that in your web function the handler is public/index.php. This properly initializes the Laravel application. Your cron functions handler is app/functions/sendTestMail.php so index.php never gets called and the Laravel kernel never handles the request.
I don't have a great solution at the moment because I feel like it is breaking a lot of best practices and rules in Laravel and want to experiment more with it. But I was able to take the entire index.php content and pasted it above my return function in the file that Lambda was calling.
So in other words I think if you paste this
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
use App\Models\Task;
define('LARAVEL_START', microtime(true));
if (file_exists(__DIR__.'/storage/framework/maintenance.php')) {
require __DIR__.'/storage/framework/maintenance.php';
}
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$response = tap($kernel->handle(
$request = Request::capture()
))->send();
$kernel->terminate($request, $response);
As the first thing in your app/functions/sendTestMail.php file, it will likely work. Depending on what you have coded in your Middleware as that will run first.
This worked for me in my application.
You can try this for the error
php artisan config:cache
php artisan config:clear
php artisan cache:clear
I would like to load vendor assets, downloaded with composer inside vendor directory, from my twig template.
Using a relative path is one solution (in this example I'm going to include bootstrap css, but the same problem is for any other libs required from composer, as jQuery, jQueryUI etc. )
<link rel="stylesheet" href="{{ asset('../vendor/twbs/bootstrap/dist/css/bootstrap.min.css') }}" >
Symfony docs suggest to use asset:install in order to generate a symlink from vendor directory to public, but I was unable to understand how it works.
assets:install -h wasn't so clear to let me understand how to link a specific vendor path to the public directory.
Creating a simlink with
ln -s /path/of/vendor/lib /path/public/dir
works fine but, symlinks created will be deleted every time I look for an update with composer.
Any idea about "a best practice" to include assets from vendor directory?
Thank you
In terms of 'Best Practice', I generally use npm with gulp or something to that effect, which generates distribution css and js files that are output to a designated file in public/.
Here's an example from a recent project package.json file
{
"devDependencies": {
"bootstrap": "^4.1.3",
"gulp": "^4.0.0",
"gulp-concat": "^2.6.1",
"gulp-sass": "^3.1.0"
},
"scripts": {
"compile:styles": "gulp styles"
}
}
Rather run npm install --save-dev bootstrap gulp gulp-concat gulp-sass to get the latest versions etc.
And you'll need this gulpfile.js too
var gulp = require('gulp');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
gulp.task('styles', function(){
return gulp
.src([
'app/Resources/sass/main.scss',
])
.pipe(sass({outputStyle:'compressed', includePaths: ['node_modules']}).on('error', sass.logError))
.pipe(concat('styles.min.css'))
.pipe(gulp.dest('public/css'));
});
Once setup, you can run npm run compile:styles from the console and the app/Resources/sass/main.scss SASS file will be pre-processed, minified and output to public/css/styles.min.css.
Note that the gulp file includes the node_modules folder so you can import bootstrap inside the main.scss file, e.g.
$primary: #55a367;
#import 'bootstrap/scss/bootstrap';
From a twig template:
<link rel="stylesheet" type="text/css" href="{{ asset('css/styles.min.css') }}">
I generally commit both the main.scss and styles.min.css
The reason why you can't tell the assets:install to link and arbitrary vendor directory is that the command is designed to loop through the list of installed bundles and link a well-known directory (Resources/public) directory if it exists. It relies on both the short bundle name and the directory existing, so it can only work with symfony bundles, there's no support for other libraries like bootstrap or jquery. (Link to current command source).
The recommended way to handle frontend libraries nowadays is encore.
In a situation where that's not possible, you could use composer scripts. I wouldn't call this "best practice", might end up being more trouble than it's worth but is an option you can consider.
You would create a shell, php script or console command where you basically replicate the functionality of assets:install to link your library assets. You will still need to manually update the script when you install a new library, but you can configure it to automatically run after installing or updating packages.
Copy this simple sample bash script into you project directory, name it install_vendors.sh:
#!/bin/bash
BASE_PATH=`pwd`
PUBLIC="public"
if [ "$1" != "" ]; then
PUBLIC=$1
fi;
PUBLIC=${BASE_PATH}/${PUBLIC}/vendor
VENDOR=${BASE_PATH}/vendor
rm $PUBLIC -rf
mkdir $PUBLIC
function link_asset
{
SOURCE_DIR=${VENDOR}/$1
TARGET_DIR=${PUBLIC}/$2
ln -s $SOURCE_DIR $TARGET_DIR
}
link_asset twbs/bootstrap/dist bootstrap
Add it to the scripts section of composer.json and the auto-scripts:
"scripts": {
"vendors:install": "bash install_vendors.sh",
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
"#vendors:install"
},
// ...
}
You can also execute it at any time with composer run vendors:install.
Then include them in your twig files: {{ asset('vendor/bootstrap/css/bootstrap.min.css') }}.
For my admin panel I extract all the assets including the manifest-json.js to mix.setPublicPath(path.normalize('public/backend/')).
All the files get correctly added to the backend folder, and the manifest-json.js file looks as follows:
{
// all correct here
"/js/vendor.js": "/js/vendor.js",
"/js/app.js": "/js/app.js",
"/css/app.css": "/css/app.css",
"/js/manifest.js": "/js/manifest.js"
}
the problem is that when using
{{ mix('backend/css/app.css') }}
in my blade-files, it looks in public/manifest-json.js instead of looking for it in backend/manifest-json.js.
How can I make sure the right manifest-json.js file is used?
I had same exception after deployment laravel project to server. It was working perfectly fine on localhost but after lot of research I found a solution. If you encounter this exception on server then you have to bind your public path to public_html
Just go to under the app/Providers, you will find your AppServiceProvider file and inside boot() method make the binding as below.
$this->app->bind('path.public', function() {
return base_path().'/../public_html';
});
i solved my problem running this command
npm install
and then
npm run production
Thank You.
The problem I faced was that the mix()-helper function by default looks for the manifest-json file in /public/manifest-json.js so if you store that file on any other directory level then it will throw that error.
Let's say the manifest-json file is stored in public/app/manifest-json.js, then for a file located in public/app/css/app.css you would use:
<link rel="stylesheet" href="{{ mix('css/app.css', 'app') }}">
The mix()-helper function allows for a second argument, the directory of the manifest file. Just specify it there and it will use the correct manifest file.
i have same problem as questioner: manifest does not exist for solving it what i have done is ran 2 commands as following:
npm install
and then
npm run dev
and the error is solved now. yippi.
In shared hosts and laravel 5.6 tested:
after doing standard levels such as explained here;
two levels needed:
in app/Providers/AppServiceProvider.php:
$this->app->bind('path.public', function() {
return realpath(base_path().'/../public_html');
});
and in public_html file make .htaccess file with content:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>
source: here
this file most change for some situations.
that's all and solved my problem
I had the same issue with a Laravel package, its assets were not published:
This solved the issue for me:
php artisan vendor:publish --tag=telescope-assets --force
Sources:
https://github.com/laravel/telescope/issues/136
https://github.com/laravel/telescope/issues/250
There are 3 ways to solve it, I summarize what the colleagues said above:
The problem is because, you are using mix() in the views.
<link rel="stylesheet" href="{{ mix('dist/css/app.css') }}">
solution 1
change it to this.
<link rel="stylesheet" href="{{ asset('dist/css/app.css') }}">
solution 2
If you don't have root access:
Modify the App\Providers\AppServiceProvider file and add the following to the boot() method.
$this->app->bind('path.public', function() {
return base_path().'/../public_html';
});
solution 3
if you have root access run:
npm install & npm run dev
try the following commands:
npm install
npm run dev
I have same exception after deployment laravel project to (shared) server when trying to reach the login and register page. It works fine on local machine.
I kept the file and folder structure the same as on my local environment (all files that our in the public folder locally are in the public_html folder on the server).
The solution mentioned above seems to work. Adapted to my file and folder structure I added the following code to AppServiceProvider file and inside boot() method.
$this->app->bind('path.public', function() {
return realpath(base_path().'/public_html');
});
The only issue now is that the CSS of the login, register and dashboard page is messed up. I'm totally new to Livewire, I have no clue how to fix that.
You should run this commands to install npm dependencies and make your frontend files:
$ npm install
$ npm run dev //or production
Now you're done and you can run your laravel project:
$ php artisan serve
In a shared hosting environment, Remove the mix e.g. {!! script(mix('js/manifest.js')) !!}
should be changed to
{!! script('js/manifest.js') !!}
This actually works for me
I got the same error
because when I run
npm install
npm run dev
I got some error.
It was fixed when I updated my nodejs version.
I'm just posting maybe someone would need it.
For me it's worked when I changed in my blade file css and js pointed path. As bellow:
In my blade was this:
<link rel="stylesheet" href="{{ mix('dist/css/app.css') }}">
I changed the MIX to ASSET as:
<link rel="stylesheet" href="{{ asset('dist/css/app.css') }}">
Also the same on JS file to:
<script src="{{ asset('dist/js/app.js') }}"></script>
If it's the same thing for everybody, in my case laravel-mix seems to be not installed so without changing any files I just installed laravel-mix by running:
npm install laravel-mix#latest --save-dev
For bind your public path to public_html, in file index.php add this 3 lines:
$app->bind('path.public', function() {
return __DIR__;
});
This is work for me on shared hosting
Try to Add your public route to your app/Providers/AppServiceProvider.php
public function register()
{
$this->app->bind('path.public',function(){
return'/home/hosting-name-folder/public_html';
});
}
Directory Structure like this
--- public
--- app
--css
--app.css
--js
--app.js
Import css js in laravel blade file like this
<link rel="stylesheet" href="{{ asset('app/css/app.css') }}">
<script src="{{ asset('app/js/app.js') }}" type="text/javascript"></script>
If you are having this issue with Laravel Nova or telescope then perhaps you are really missing mix-manifest file. You should have that file inside public/vendor/toolname/
Where toolname can be Nova or Telescope. If you have that folder, you should go ahead and put in your server otherwise you will first have to publish the assets & then put it on server.
I change resources/layouts/guest.blade.php and resources/layouts/app.blade.php
<!-- Styles -->
<link rel="stylesheet" href="{{asset('css')}}/app.css">
<!-- Scripts -->
<script src="{{asset('css')}}js/app.js"></script>
and resources/css and resources/js copy my public folder
The Mix manifest does not exist.
You can solve this problem by updating the node version.
actually when you run command npm run dev,
show the error message "Error: You are using an unsupported version of Node. Please update to at least Node v12.14"
so easily you can fix it by updating the node js version
Thanks
if your previous setup is correct.but you are looking this type of error it shows The Mix manifest does not exist. then write these command .
npm ci
npm run dev
I resolved my problem by this command :
npm install
npm run dev
Worked for me on a fresh install of Laravel 9 with Jetstream(using Laradock).
npm run install && npm run development
When running npm run dev the mix was not compiling the files and creating the mix-manifest.json
step1
npm install
npm run production
step 2
refresh by simply closing and opening the project
step 3
replace <link rel="stylesheet" href="{{ mix('css/app.css') }}">
with
<link rel="stylesheet" href="/css/app.css/">
Here you go!!!!!
I got the same problem when hosting on cpanel
just change from
{{ mix('backend/css/app.css') }}
Becomes
{{ asset('backend/css/app.css') }}
it's solve my problem.
don't forget to upvote if this answer help u
There are a lot of answers to these questions, I am posting this question just in case if any miss these points.
Method: 1
Make sure to check the .gitignore file. sometimes it's listed there and doesn't make the file be pushed to git repo
Method: 2
Add this code in webpack.mix.js so you will exactly know where it's placing the mix-manifist.json file
mix.webpackConfig({
output: {
path: __dirname + "/public"
}
});
I had the issue on a shared host, where I was not able to run npm commands. Then I used the simplest way. In the /vendor/laravel/.../Foundation/Mix.php replace
i$manifests[$manifestPath] = json_decode(file_get_contents($manifestPath), true);
to
$manifests[$manifestPath] = json_decode(file_get_contents('https://your-domain.com/mix-manifest.json'), true);
Not recommended, but it works. You can use it as your last try.
Faced the same problem on both Windows and Ubuntu. Solved it on Ubuntu (and I presume the solution is simillar in Windows). The problem was due to the fact that my installed npm version was too old.
The solution for me was the following. I installed nvm (NodeVersionManager -version 0.39.1) which allowed me to switch to the latest stable version of node (v16.14.0) and then install npm 8.5.0.
Detailed steps:
Linux bash terminal commands:
touch ~/.bash_profile ~/.bashrc ~/.zshrc ~/.profile
sudo apt install curl
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
logout and login Ubuntu user
nvm --version
nvm ls-remote
nvm install 16.14.0
node --version
...then inside the laravel project:
npm ci
npm install -g npm#8.5.0
npm audit fix
npm run dev
Try out this one!!
<script src="{{ asset('js/app.js') }}" defer></script>
It works for me
I found new solution
The problem is mix manifest right?
So just redirect to the mix manifest feature. for example, you have:
{{ style(mix('css/backend.css')) }}
just change your code into
{{ style('css/backend.css') }}
it works for me
I use Laravel framework as Restful API server, and React as SPA client render and for routing i have used react create app kit, I build React project. I get app.js and app.css files by type npm run build.
How to use this file with Laravel?
How use react routing?
How to deploy it correctly?
I can answer your questions and have an example.
Basically, to use Laravel as an API backend for a React (or JS) Single-Page application:
setup a Laravel project - it's the backend, so setup it and the routes you want
1.a Suggestion Make your URLs for the SPI separate/distinct from normal URLs your Laravel app itself might use for page requests or other things (such as "/api/...").
1.b Laravel (5+ or so, my example is 5.1) comes packaged with a Gulp/build tool called "Elixir". It's setup to look for things like scripts files and views in the resources/... directory, so I suggest putting your scripts in some place like resources/assets/scripts/app.js or something.
1.c (Build Process) Assuming you put your React scripts in resources/assets/script, then when you run "gulp" and the Elixir task runs for building the app, it will put the bundled, app.js file into public/js/app.js -- Laravel views by default think of the public/ directory as their root directory, so you can reference that built file in your index page as "js/app.js".
1.d If Gulp or Elixir are unfamiliar to you, I encourage you to give this page a read for an overview:
https://laravel.com/docs/5.1/elixir
setup the Routes for Laravel, your Index page and the API stuff. I suggest routing '/' and all NON-API (or known) routes to just make the Index page View, where we'll load the app.js ReactJS application file.
2.a It's worth noting that in my example, currently, I have not implemented the React Router, so I'm leaving all React routes alone for the moment. I'm assuming this is something you know since your questions seems to be "how to make the Backend be Laravel".
Route::get('/', function () { return View::make('pages.index'); });
Route::group(['prefix' => 'api'], function () {
Route::get('tasks', 'TodosController#index');
});
2.b Setup the Routes to map requests to controller actions, where you can customize your response. For example, you can respond with JSON for a JSON API:
TodosController#index
$current_tasks = array(
array("id" => "00001", "task" => "Wake up", "complete" => true),
array("id" => "00002", "task" => "Eat breakfast with coffee power", "complete" => true),
array("id" => "00003", "task" => "Go to laptop", "complete" => true),
array("id" => "00004", "task" => "Finish React + Laravel Example app", "complete" => false),
array("id" => "00005", "task" => "Respond on StackOverflow", "complete" => false)
);
return response()->json($current_tasks);
As far as deployment goes, you'll probably need to build the code (my example does) and load the built version of the code into your production Index page or wherever. You'll also deploy it overall as a laravel app -- you want Laravel seeing the Routes first externally and want React to handle it's own URLs and routes. This way, say you expand the SPA but want the same backend, you just add routes to your Laravel app as exceptions/overrides in the routes file.
resources/pages/index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>BLaravel 5.1 + ReactJS Single-Page App</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<link rel="stylesheet" href="css/app.css" />
<!-- BACKUP SCRIPT CNDS, for React -->
<!-- <script src="https://unpkg.com/react#15/dist/react.js"></script> -->
<!-- <script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script> -->
</head>
<body>
<!-- Container for React App -->
<div class="container" id="react-app-container"></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Because there's (as far as I know) no Plnkr for this sort of thing, I made a local development version of Laravel + React to illustrate my way of making the kind of app you seem to be asking for. It's currently hosted on my GitHub account, so feel free to clone it and follow the README and use it if it helps, or ask for edits/help/clarification.
https://github.com/b-malone/Laravel5-ReactJS-Boilerplate.git
Build/Setup Commands (Reference)
git clone ... [TEST/] && cd into [TEST/]
composer install
npm install
cp .env.example .env
gulp
php artisan serve
visit http://localhost:8000
Please find the steps to run app in your local machine
Step 1:
Download the code from git
Step 2:
Composer install
Step 3:
Npm install
Please do following steps if you face - cross-env NODE_ENV=development webpack --progress --hide-modules --
You need to make cross-env working globally instead of having it in the project.
1) remove node_modules folder
2) run npm install --global cross-env
3) remove "cross-env": "^5.0.1", from package.json file devDependencies section. Actually, you can skip this step and keep package.json intact. If you prefer.
4) run npm install --no-bin-links
5) run npm run dev
Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command
Step 4:
Npm run dev
Step 5:
Php artisan serve
we can simplify our task by this bash script.ssh
#!/bin/bash
#install updates
sudo apt-get update
sudo apt-get upgrade
#install nginx
sudo apt-get install nginx
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash
#install nodejs
sudo apt-get install -y nodejs
#status of install ndoe and nginx
node -v
sudo service nginx status
#clone repo of project in server
git clone https://github.com/your_new_project.git
cd your_new_project
npm run build
#(first time,it downlod lib,and files )
npm run build
#(second time,he build and run it)
cd build/
ls
ls static/
#now tell nginx server (listen :80/ root :path of build folder/ location :index.html)
Create a project file
sudo nano /etc/nginx/sites-available/react_counter
server {
server_name your_IP domain.com www.domain.com;
root /home/username/React-counter-app/build;
index index.html index.htm;
location / {
try_files $uri /index.html =404;
}
}
server_name put your IP address
root we use this to give the server the application located in the disk
index The main file
Enable the file by linking to the sites-enabled dir
sudo ln -s /etc/nginx/sites-available/react_counter /etc/nginx/sites-enabled
Test NGINX config
$ sudo nginx -t
Restart Nginx Server
$ sudo systemctl restart nginx
Open your browser and go to http://youripaddress
Thanks for reading. #syedasadrazadevops