custom name for root in route in laravel 5.5 - laravel

I use these routes
Route::namespace('Panel\Admin')->prefix('admin')->group(function (){
$this->get('/', 'HomeController#index');
$this->namespace('Users')->prefix('users')->group(function (){
$this->get('/' , 'UserController#index')->name('users');
$this->delete('/{user}/destroy' , 'UserController#destroy')->name('users.destroy');
$this->get('/create' , 'UserController#create')->name('users.create');
$this->post('/store' , 'UserController#store')->name('users.store');
$this->get('/{user}/edit' , 'UserController#edit')->name('users.edit');
$this->patch('/{user}/update' , 'UserController#update')->name('users.update');
it works.
for example with php artisan route:list I have these:
admin/users | users
admin/users/create | users.create
admin/users/store | users.store
admin/users/{user}/destroy | users.destroy
But I want write the code short:
Route::namespace('Panel\Admin')->prefix('admin')->group(function (){
$this->get('/', 'HomeController#index');
$this->namespace('Users')->prefix('users')->group(function (){
$this->resource('/' , 'UserController');
$this->resource('/test' , 'UserController');
with php artisan route:list I have these:
admin/users | index
admin/users | store
admin/users/create | create
admin/users/{} | show
admin/users/{} | update
admin/users/{} | destroy
admin/users/{}/edit | edit
It's wrong. but for test is correct. for example:
admin/users/test | test.store
admin/users/test/{test}/edit | test.edit
what is my wrong?

$this->resource('user' , 'UserController');
That will create all of your standard routes for users.
You should not include the prefix user, since it will create that.

The first parameter of resource method should be a name for the resource,
so you should remove the users prefix and add users as name for the resource
$this->resource('users' , 'UserController');
you can read more about it on the documentation

Related

Laravel | Route not defined

I have a problem in my Route.
I see this error:
Route [utilizadores.editar] not defined
The error occurs on the page when I try to update the data in my DB.
My Route:
Route::put('Utilizadores/{item}', [FuncionarioController::class, 'editar'])->name('utilizadores.editar');
Route::get('Utilizadores/{item}/edit', [FuncionarioController::class, 'edit'])->name('utilizadores.edit');
My controller:
public function editar(Request $request, funcionario $item){
$item->nome = $request->nome;
$item->email = $request->email;
$item->telefone = $request->telefone;
$item->foto = $request->foto;
$item->data_nasc = $request->data_nasc;
$item->nacionalidade = $request->nacionalidade;
$item->n_cartao_cc = $request->n_cartao_cc;
$item->nif = $request->nif;
$item->morada = $request->morada;
$item->n_porta = $request->n_porta;
$item->localidade = $request->localidade;
$item->concelho = $request->concelho;
$item->distrito = $request->distrito;
$item->cp = $request->cp;
$item->data_entrada = $request->data_entrada;
$item->funcao = $request->funcao;
$item->estado = $request->estado;
// $item->n_ferias_disponiveis = $request->n_ferias_disponiveis;
// $item->data_registo = $now;
dd($item);
$item->save();
return redirect()->route('utilizadores.index');
}
My View:
<form class="needs-validation" method="POST" action="{{route('utilizadores.editar',$item->id)}}" enctype="multipart/form-data">
#csrf
#method('put')
Where am I wrong? I have other pages like this done and it works.
Thanks to anyone who can help me.
Edit: My php artisan route:list
| | DELETE | Utilizadores/{item} | utilizadores.delete | App\Http\Controllers\FuncionarioController#delete | web
|
| | PUT | Utilizadores/{item} | utilizadores.editar_perfil | App\Http\Controllers\FuncionarioController#editar_perfil | web
|
| | GET|HEAD | Utilizadores/{item}/delete | utilizadores.modal | App\Http\Controllers\FuncionarioController#modal | web
|
| | GET|HEAD | Utilizadores/{item}/edit | utilizadores.edit | App\Http\Controllers\FuncionarioController#edit | web
|
| | GET|HEAD | Utilizadores/{item}/edit_perfil | utilizadores.edit_perfil | App\Http\Controllers\FuncionarioController#edit_perfil | web
|
| | PUT | Utilizadores/{item}/editpass | utilizadores.passwordeditar | App\Http\Controllers\FuncionarioController#passwordeditar | web
Just swap edit and editar route. Something like this
Route::get('Utilizadores/{item}/edit', [FuncionarioController::class, 'edit'])->name('utilizadores.edit');
Route::put('Utilizadores/{item}', [FuncionarioController::class, 'editar'])->name('utilizadores.editar');
Or better, use resource controller for simpler Route file
Route::resource('utilizadores', FuncionarioController::class);
Keep in mind that you will tweak some function name and route file
Docs
You cannot have two identical routes for the same method/path. It is apparent in route:list that you already have a route registered for put('Utilizadores/{item}') with a different name (utilizadores.editar_perfil), therefore,
Route::put('Utilizadores/{item}',
[FuncionarioController::class, 'editar'])
->name('utilizadores.editar');
is not being registered, so you get that error when you try to insert {{ route('utilizadores.editar',$item->id) }} in your view.
First look to your route list using below command
php artisan route:list
If the routes exists then hit this command :
php artisan optimize
php artisan optimize:clear

Laravel - could not find driver

I'm experiencing the error:
could not find driver (SQL: select * from sessions where id = Kz9rXIxivkq0sVfLu4ypMLQA3ePNZccHjsRZUhml limit 1)
see image
Migrations are running fine which is strange. Here is my php -m output:
[PHP Modules]
bz2
calendar
Core
ctype
curl
date
dom
exif
fileinfo
filter
ftp
gd
gettext
hash
iconv
json
libxml
mbstring
mysqli
mysqlnd
openssl
pcntl
pcre
PDO
pdo_mysql
pdo_sqlite
Phar
readline
Reflection
session
SimpleXML
sockets
SPL
sqlite3
standard
tokenizer
wddx
xml
xmlreader
xmlwriter
xsl
zip
zlib
[Zend Modules]
Also for some reason, all PHP scripts are running very slowly, even simple ones (php -v, php --ini). Application is running on nginx server.
Does anyone know how to resolve this? Thank you very much in advance!
EDIT
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', 240),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| 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' => false,
/*
|--------------------------------------------------------------------------
| 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', null),
/*
|--------------------------------------------------------------------------
| 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
|--------------------------------------------------------------------------
|
| When using the "apc", "memcached", or "dynamodb" session drivers 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".
|
*/
'store' => env('SESSION_STORE', null),
/*
|--------------------------------------------------------------------------
| 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' => [100, 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', null),
/*
|--------------------------------------------------------------------------
| 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 if it can not be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE', false),
/*
|--------------------------------------------------------------------------
| 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
| do not enable this as other CSRF protection services are in place.
|
| Supported: "lax", "strict"
|
*/
'same_site' => null,
];
enter code here
enter code here
.env
APP_NAME=LARAVEL
APP_ENV=development
APP_KEY=base64:MEw1jEc7qyYhz4vIgxpZIqbURtoQ67HS6KsSBajwMC0=
APP_DEBUG=true
APP_URL=127.0.0.1
LOG_CHANNEL=single
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=app_prod
DB_USERNAME=root
DB_PASSWORD=SomePassword
#SESSION_SECURE_COOKIE=true
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=database
SESSION_DRIVER=anonymous-database
SESSION_LIFETIME=120
ACCESS_ALLOW_IP=
ACCESS_ALLOW_IP_ON=false
Managed finally to fix it. I just did yum -y remove php* and installed everything again.
Yeah as defined in your .env file you have defined the SESSION_DRIVER to anonymous_database it must be file or mysql or any prefered database driver. As your program is trying to retrieve session from database there must be a table of sessions present there.
For the proper session table schema it is defined in : https://laravel.com/docs/6.x/session#driver-prerequisites

Laravel connection with postgres doesn't work properly

I'm just setting up a new Laravel installation with a postgressql server using a role with NO superuser privileges (test). I'm using Manjaro to test and I've installed php 8 and enabled/installed php-pgsql with pgsql and pdo_pgsql extensions uncommented at /etc/php/php.ini
Laravel does seem to detect the table but it can't run migrations. These are the commands I'm using:
php artisan migrate:install (this one works)
php artisan migrate:status (this one doesn't work, it can't find the migrations table)
Also this is my .env (the relevant piece):
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=test
DB_USERNAME=test
DB_PASSWORD=
This is what I get from the test user within laravel:
test=> \l
postgres | postgres | UTF8 | es_CL.utf8 | es_CL.utf8 |
template0 | postgres | UTF8 | es_CL.utf8 | es_CL.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | es_CL.utf8 | es_CL.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
test | test | UTF8 | es_CL.utf8 | es_CL.utf8 |
For command migrate:status, Laravel calls this method in internal class PostgresGrammar in namespace Illuminate\Database\Schema\Grammars.
/**
* Compile the query to determine if a table exists.
*
* #return string
*/
public function compileTableExists()
{
return "select * from information_schema.tables where table_schema = ? and table_name = ? and table_type = 'BASE TABLE'";
}
If you see it select records from information_schema which needs proper permissions to work. The user, in your case test, needs to be the owner of the schema, which is test in your case, to get any rows from information_schema.tables which are related to your schema.
run this command to change the owner of the schema:
alter schema `test` owner to `test`;
Or the user needs to be a member of a group that owns the schema.
Note:
Usage grant is not sufficient. The user does not need to be a superuser. The user can own a table in a schema, but that is not sufficient either.
Refs:
What permissions are required to return rows from information_schema.schemata?
PostgresGrammar Implementation

Protect Responsive FileManager from direct access

I am using responsive FileManager 9.14.0 with TinyMCE 5.0.16 and Laravel 6 running on Nginx 1.16.1
I have the following folder structure:
| public
| |- uploads
| |- thumbs
| |- filemanager
| |- js
| | |- tinymce
| | | |- plugins
| | | | |- responsivefilemanager
| | | | | |- plugin.min.js
I use laravel authentication to protect a 'create' page where the user can add text using tinyMCE and upload images using RFM as tyniMCE plugin.
But RFM is accessible directly if with the following URL
http://www.myhost.test/filemanager/dialog.php
How can I prevent this behavior. I want RFM to be accessible only from the tinyMCE editor.
im not familier with laravel but ...
in Responsive File Manager 9.0 there is a folder called config that contain config.php
| public
| |- uploads
| |- thumbs
| |- filemanager
| | |- config
| | | |- config.php
| |- js
| | |- tinymce
| | | |- plugins
| | | | |- responsivefilemanager
| | | | | |- plugin.min.js
open config.php and change
define('USE_ACCESS_KEYS', false); // TRUE or FALSE -------- to ------> define('USE_ACCESS_KEYS', true); // TRUE or FALSE
this force Responsive File Manager to use Aaccess Key to prevent all attempt from being accessed to your files and folders.
in same file at line 190 add your users auth_key for whom they need to use file-manager .
for example :
username: jim auth_key: a1s2d3f4g5h6j7k8l9mm
username: lisa auth_key: zqxwd3f4vrbth6j7btny
so line 190 should rewrite like line below:
'access_keys' => array( "a1s2d3f4g5h6j7k8l9" , "zqxwd3f4vrbth6j7btny"),
go to your form and add a button/link to access RESPONSIVE FILE MANAGER
<a href="https://www.example.com/admin/responsive-filemanager/filemanager/dialog.php?akey=<?php echo {{{your authenticated user AUTH_KEY}}}; ?> </a>
if there is no {{{your authenticated user AUTH_KEY}}} there is 2 way:
1)) add a column auth_key to your users table and generate auth_key that should be equal for users they want to access to responsive file manager in both database and config.php file.
2)) use username instead of auth_key so your config at line 19 will be:
'access_keys' => array( "jim" , "lisa"),
and now your responsive file manager access link will be like this:
<a href="https://www.example.com/admin/responsive-filemanager/filemanager/dialog.php?akey=jim ></a>
jim is static here u should make it dynamic by call function to return authenticated user USERNAME and put it after &akey= in link
now if akey value in link find in access_key array the responsive file manager page will be work otherwise it show you ACCESS DENIED!!!
If it's still relevant, I can show you how I did it in Laravel 8
I proceeded from the opposite - if the user logged in under the admin, then there is no need to check it and therefore USE_ACCESS_KEYS do FALSE, otherwise - TRUE
And therefore, if he is NOT authenticated as an administrator, then he will NOT get access to the ResponsiveFileManager.
To do this, add such a function in the responsive_filemanager / filemanager / config / config.php file somewhere at the beginning of the file.
( Specify your own paths to the files '/vendor/autoload.php' and '/bootstrap/app.php' )
function use_access_keys() {
require dirname(__DIR__, 4) . '/vendor/autoload.php';
$app = require_once dirname(__DIR__, 4) . '/bootstrap/app.php';
$request = Illuminate\Http\Request::capture();
$request->setMethod('GET');
$app->make('Illuminate\Contracts\Http\Kernel')->handle($request);
if (Auth::check() && Auth::user()->hasRole('admin')) {
return false;
}
return true;
}
and then this line:
define('USE_ACCESS_KEYS', false);
replace with this:
define('USE_ACCESS_KEYS', use_access_keys());
And one moment.
If after that, when opening the FileManager, the following error suddenly pops up: "Undefined variable: lang"
then open responsive_filemanager / filemanager / dialog.php
find the array $get_params and in it change like this:
'lang' => 'en',

Laravel seems to be caching API routes despite my attempts to clear - ideas?

I have Laravel 5.3 site.
I added some api routes today but they are not called.
Indeed I have a NewRouteController file under Http/Api
But the route returns 404 error. The controller is never reached.
There are other routes in api.php that work fine (call one of them api/workingroute, for instance). But if I comment out their route in api.php, they still work!
Here is the api.php file:
Route::group(['prefix' => 'api'], function () { Route::resource('workingroute', 'Api\WorkingRouteController'); });
Route::group(['prefix' => 'api'], function () { Route::resource('newroute', 'Api\NewRouteController'); });
I think the problem is revealed by route:list
GET|HEAD | api/api/newitems | newitems.index | App\Http\Controllers\Api\New RouteController#index | api |
| | POST | api/api/newitems | newitems.store | App\Http\Controllers\Api\New Route#store | api |
| | GET|HEAD | api/api/newitems/create | newitems.create | App\Http\Controllers\Api\New Route#create | api |
| | GET|HEAD | api/api/newitems/{newitem} | newitems.show | App\Http\Controllers\Api\New Route#show | api |
| | DELETE | api/api/newitems/{newitem} | newitems.destroy | App\Http\Controllers\Api\New Route#destroy | api |
| | PUT|PATCH | api/api/newitems/{newitem} | newitems.update | App\Http\Controllers\Api\New Route#update | api |
| | GET|HEAD | api/api/newitems/{newitem}/edit | newitems.edit | App\Http\Controllers\Api\New Route#edit | api
Not sure why we have api/api since I don't see anywhere where I would have indicated the route that way, especially since I am just repeating everything that exists for working api routes. Or I suppose since I am using api.php that the prefix is already added.
Also, odd that for my working route, I have a bunch of entries of form api/route, but they also have repeat entries of form api/api/route
And for routes of form api/api/item we have these sorts of lines
api/api/item/{item} | item.show | App\Http\Controllers\Api\ItemController#show | api
For routes of form api/item these sorts of lines:
GET|HEAD | api/item/{item} | lesson.show | App\Http\Controllers\Api\ItemController#show | web,auth,admin
I looked at routes.php which is holdover from Laravel 5.2 which is still in my folder structure, and we have these sorts of lines:
// Api
Route::group(['middleware' => ['api', 'auth', 'admin']], function () {
Route::group(array('prefix' => 'api'), function() {
RegisterResourceRoute('item', 'Item');
I think maybe I broke something when I upgraded from 5.2 to 5.3. Strangely enough, the routes defined by this routes.php are the ones of form api/item, and they work. The question now is what to do to get routes back to normal, so that all api routes are of form api/item and all have web,auth,admin?
ALso, for what it is worth (not sure if cacheing somehow influences my issue), there is .gitignore in the bootstrap/cache folder as well as all storage folders.
And here is cache.php:
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache'),
],
'memcached' => [
'driver' => 'memcached',
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
'prefix' => 'laravel',
];
Ideas?
Thanks,
Brian
I suspect several things have happened, but in short check your bootstrap/cache folder. In it I hope you will find a file called routes.php and it has probably been committed into your repo and now you've pulled it down or maybe you even accidentally created it yourself when playing with artisan commands.
Canonically you would use php artisan route:clear but if your command line isn't working that won't work, however you should be ok to delete it.
If this is the case, it was created with php artisan route:cache but it is advisable only to use that on your production server (possibly as part of a deploymnet script or perhaps as a git hook.)
Ideally there would be a .gitignore (if you're using git) file in the cache folder to avoid this sort of thing being transmitted between different developers.
(Edit - this is only true for later versions of Laravel, but not 5.3 - the OP's version. I leave this here in case other people have the same problem.) It is also possible that someone (if you're working in a team) has done all this on purpose and just not communicated the changes. If so it's also possible that they have specifically set another path for route caching using the environment variable 'APP_ROUTES_CACHE' in which case you'll have to look there.
Sorry this is so complicated - but because of the flexibilty of laravel there are many different ways this could be happening. Please do try them all, though - this is almost certainly a caching issue.

Resources