Form open to controller method - "Unknown action" - laravel

New to Laravel 4. I've created a form within a blade template and I'm following the snippet from which says that you can point a forms action to a controller method by using 'Form::open(array('action' => 'Controller#method'))'. I've created a new controller called UsersController with artisan and have created a new method within the controller named userLogin(). When I point to that method when opening a form I get an "InvalidArgumentException, Unknown action" error. If I adjust the open action to point to UsersController#index, all is well. I've run composer dump-autoload, but the issue remains.
snippet of login.blade.php:
{{ Form::open(array('action' => 'UsersController#userLogin')) }}
snippet of UsersController.php:
public function userLogin()
{
//
}
Can anyone tell me if I'm missing something?
Thanks all. Adding the following to routes.php resolved the issue:
Route::post('login', 'UsersController#userLogin');

Looks like Laravel isn't registering the action you've added, likely because you're missing a route. Try adding something like this to app/routes.php:
Route::post('user/login', 'UsersController#userLogin');

After adding the route to your routes.php, did you also change Form::open()? If not, you can just have your Form post to /login or /user/login.
Also, just because I'm a bit of a stickler for these sort of things, it's common practise to have controllers and models as singular, so UsersController would be UserController, and since the login function is within User(s)Controller, it doesn't need the user prefix. May help your code be more readable :)

Now in laravel 4 you can use this :
Route::post('/signup', array('before' => 'csrf', 'uses' => 'UsersController#userLogin'));

Related

Laravel using of resource

I'm new to Laravel and I'm working around with it.
I have a folder in views called 'cp'. in cp folder I can add/remove new slider through index.blade.php and also add new products through product.blade.php. I want to update my products too but when I submit the form It goes to the wrong route ( blog.dev/product/6 ).
I also attached 4 screenshots that shows the pages.
Could you please help me with that.
This is web.php:
Route::get('/','PagesController#index');
Route::get('درباره-ما', 'PagesController#about');
Route::get('تماس-با-ما', 'PagesController#contact');
Route::get('غذای-سگ', 'PagesController#dogs');
Route::get('/cp/product', 'ProductController#product');
Route::get('/cp/product/{id}/edit/', 'ProductController#edit');
Route::resource('product','ProductController');
Route::resource('cp', 'PostsController');
Auth::routes();
screenshot1: https://cdn.pbrd.co/images/GSFDbPj.jpg
screenshot2: https://cdn.pbrd.co/images/GSFDNRq.jpg
screenshot3: https://cdn.pbrd.co/images/GSFEi1a.jpg
screenshot4: https://cdn.pbrd.co/images/GSFCI6F.jpg
Laravel read the route from the top and stop at the first match, so put the more restrictive route at the top
Try something like this : (unfortunately I can't check the non-latin alaphabet, maybe you can also comment them if you still have issue - just to be sure it's not a cause too)
Route::get('/','PagesController#index');
Route::get('درباره-ما', 'PagesController#about');
Route::get('تماس-با-ما', 'PagesController#contact');
Route::get('غذای-سگ', 'PagesController#dogs');
Route::get('/cp/product/{id}/edit/', 'ProductController#edit');
Route::get('/cp/product', 'ProductController#product');
Route::resource('product','ProductController');
Route::resource('cp', 'PostsController');
Auth::routes();
Can you tell me if it's working ?
update method available only PUT|PATCH method
change your request url
/product/6?_method=PUT
now you can use POST method for update

laravel routing based on convention

I'm trying to setup a simple routing system based on convention.
My app will have this structure
Http
--Controllers
----Admin
------User.php
----Books
------Add.php
----etc...
I want to be able to add new Folders and controllers without adding routes manually to the web.php file.
For example I want the route to respond to /Admin/User URL with User.php controller.
I'm trying something like this, but I don't understand how to write the internal router...
Route::any('/{module}/{action?}', function($module, $action = 'index') {
Route::get('*',$module.'\'.$action.'#index' );
});
It seems that Rout:get('*'... never matches.
PS the controller namespace is correct and I reloaded with composer.
The controller works if called harcoded.
I tried also to escape '\'
$r=$module.'\\'.$action.'\\'.$action.'Ctl#index';
Route::get('/',$r );
But no result. The route is intercepted but nothing i served
It seems I came up with this
Route::get('/{module}/{action}', function($module,$action) {
return App::make('\App\Http\Controllers\\'
.$module.'\\'.$action)->callAction('index', []);
});
Any other better way?

How can I render a twig template in a custom controller in Silex?

I'm playing with Silex microframework to build a very simple app.
The Silex documentation briefly illustrates how to keep your code organised using controller as class and I've also found this useful article talking about the same practice:
https://igor.io/2012/11/09/scaling-silex.html
but still can't solve my problem
The issue:
in my app.php I'm using
$app->get('/{artist}', 'MyNamespace\\MyController::getAlbum');
This is working. MyController is a class correctly loaded through composer using psr-4.
At the moment the return method of getAlbum($artist) is return $player;
What I'd like to do instead, is returning a twig view from getAlbum, something like:
return $app['twig']->render('player.twig', $player);
To do so, what I've tried to do in my custom class/controller is:
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
[...]
public function getAlbum(Request $request, Application $app, $artist)
but this is generating the following error when I try to access the routed pages:
ReflectionException in ControllerResolver.php line 43:
Class MyNamespace\Request does not exist
Whic made me think that there's a namespace conflict between myNamespace and the Silex namespaces?!
What am I doing wrong?
Is this the right way to make $app visible in my custom controller in order to use return $app['twig']... ?
Thank you in advance!
EDIT
After several other tries still didn't get to the point (replies still welcome!) but I've found a workaround solution that could be useful to anyone will incur in a similar issue. Directly in my app.php I added this
$app->get('/{artist}', function (Silex\Application $app, $artist) use ($app)
{
$object = new MyNamespace\MyController();
$player = $object->getAlbum($artist);
return $app['twig']->render('player.twig',
array(
//passing my custom method return to twig
'player' => $player,));
});
then in my player.twig I added:
{{player | raw}}
And this basically means that I still need an anonymous function to get use of my custom method which is a working solution I'm not really happy with because:
I'm using 2 functions for 1 purpose.
The return value of getAlbum is dependent from the use of "raw" in twig.
SOLVED
The workflow described works fine. It was a distraction error: I've placed the namespace of my custom class after use Symfony\Component\HttpFoundation\Request;
namespace declaration in PHP needs always to be at the top of the file, Silex wasn't able to injects $app and $request for this reason.

Subfolder routing in laravel 5

I am having trouble routing with controllers in subfolders. I have tried the solution proposed in Laravel Controller Subfolder routing, but I can't get it to work.
Folder structure
HTTP
Controllers
Admin
AdminControllers
User
UserControllers
BaseController
Admincontrollers are defined in the 'App\HTTP\Controllers\Admin' namespace
Routes file
Route::group(['middleware'=> 'admin','prefix' => 'admin'], function() {
Route::get('home', 'AdminHomeController#index');
Route::get('home', 'Admin\AdminHomeController#index');
Route::resource('events', 'AdminEventController');
Route::resource('events', 'Admin\AdminEventController');
Route::get('myevents', 'AdminEventController#myevents');
Route::get('myevents', 'Admin\AdminEventController#myevents');
Route::resource('groups', 'AdminGroupController');
Route::resource('users', 'AdminUserController');
});
This does seem weird, but it is the only way to keep it working right now.
If I delete
Route::get('myevents', 'Admin\AdminEventController#myevents');
//errormessage Class App\Http\Controllers\AdminEventController does not exist
If I delete
Route::get('myevents', 'AdminEventController#myevents');
//errormessage Action App\Http\Controllers\AdminEventController#myevents not defined.
If I put the controllers in the controller namespace (not the admin one)
I still get
//errormessage Class App\Http\Controllers\AdminEventController does not exist
When the only route added is
Route::resource('events', 'AdminEventController');
The problem were the calls in the views:
changing
<td>{!!Html::linkAction('AdminEventController#show', $event->name, $event->slug)!!}</td>
to
<td>{!!Html::linkAction('Admin\AdminEventController#show', $event->name, $event->slug)!!}</td>
fixed it.
The Laravel 5 solution in Laravel Controller Subfolder routing is correct. The problem was not in the routes file or controllers.
Yes If your application gets bigger like this, it makes sense to structure Controllers with sub-folders. But it takes a little more effort than just moving the files here and there. Let me explain the structure.
For example, we want to have a sub-folder app/Http/Controllers/Admin and then inside of it we have our AdminController.php, that’s fine. What we need to do inside of the file itself:
Correct namespace – specify the inner folder:
namespace App\Http\Controllers\Admin;
Use Controller – from your inner-namespace Laravel won’t “understand” extends Controller, so you need to add this:
use App\Http\Controllers\Controller;
Routes – specify full path
This wouldn’t work anymore:
Route::get('admin', 'AdminController#index');
This is the correct way:
Route::get('admin', 'Admin\AdminController#index');
And that’s it – now you can use your controller from sub-folder.
Reference (Tested):
http://laraveldaily.com/moving-controllers-to-sub-folders-in-a-correct-way/
By: Povilas Korop

How to set view file path in laravel?

I have a directory structure for laravel app like this:
app/
admin/
controllers/
views/ -> for admin views
...
views/ -> for frontend views
How can I set the view path for controllers in admin? I don't want to use View::addLocation or View::addNamespace because I might have the same view file name for admin and frontend, and don't want to add a namespace for every View::make('namespace::view.file').
I see in http://laravel.com/api/4.2/Illuminate/View/View.html there is a setPath method, but how do I call it? View::setPath raised undefined method error.
You have two ways to accomplish your goal. First, let's have a look at app/config/view.php. That's where the path(s) for view loading are defined.
This is the default:
'paths' => array(__DIR__.'/../views'),
Method 1: Load both directories
You can easily add the admin directory to the array
'paths' => array(
__DIR__.'/../views',
__DIR__.'/../admin/views
),
Now the big disadvantage of this: view names have to be unique. Otherwise the view in the path specified first will be taken.
Since you don't want to use a view namespace I suppose you don't want a syntax like admin.viewname either. You'll probably like method 2 more ;)
Method 2: Change the view page at runtime
Every Laravel config can be changed at runtime using the Config::set method.
Config::set('view.paths', array(__DIR__.'/../admin/views'));
Apparently setting the config won't change anything because it is loaded when the application bootstraps and ignored afterwards.
To change the path at runtime you have to create a new instance of the FileViewFinder.
Here's how that looks like:
$finder = new \Illuminate\View\FileViewFinder(app()['files'], array(app_path().'/admin/views'));
View::setFinder($finder);
Method 3: Use addLocation but without default path
You could also remove the default path in app/config/view.php
'paths' => array(),
And then use View::addLocation in any case (frontend and admin)
View::addLocation(app_path().'/views');
View::addLocation(app_path().'/admin/views');
In the latest version 6 i am doing it this ways:
View::getFinder()
->setPaths([
base_path('themes/frontend/views'),
base_path('themes/admin/views')]
)
In Laravel 5.5, other solutions did not work. In boot method of a service provider
View::getFinder()->prependLocation(
resource_path('views') . '/theme'
);
try it like this
View::addNamespace('admin', app_path() . '/admin/views');
Route::group(['prefix' => 'admin'], function() {
Route::get('/', function() {
return view('admin::index');
});
});

Resources