Laravel 5 - Can't route to controller - laravel

I'm having an issue routing in laravel 5. My code is:
<?php
Route::get('/', function () {
return "Ok";
});
//Authentication Routes
Route::post("/authenticate", "AuthenticationController#Authenticate");
Route::post("/register", "AuthenticationController#Register");
If i place the inline functions, it all works well, however when I try the controller way, it just outputs a blank page.
Any ideas?
Edit: Here's the controller
<?php
namespace App\Http\Controllers;
use User;
use Auth;
use Input;
use Hash;
use Illuminate\Routing\Controller as BaseController;
class AuthenticationController extends BaseController
{
public function Authenticate() {
if(Auth::attempt([ 'email'=>Input::get('email'),
'password'=>Input::get('password')]))
{
return response()->json("OK");
}
else
{
return response()->json("ERROR");
}
}
public function Register() {
return response()->json("Not Implemented");
}
}

You're extending the wrong Controller here:
use Illuminate\Routing\Controller as BaseController;
Also set in your .env file debug=true to see what the Error is.
Probably is controller related issue.
You should extend the Controller within your app\Http\Controllers\ folder. (which falls within the same namespace). Especially to get ValidatesRequests trait working (really useful!).
Fix your controller by removing the:
use Illuminate\Routing\Controller as BaseController;
Example:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Hash;
class AuthenticationController extends Controller
{
public function Authenticate() {
if(Auth::attempt([ 'email'=>Input::get('email'),
'password'=>Input::get('password')]))
{
return response()->json("OK");
}
else
{
return response()->json("ERROR");
}
}
public function Register() {
return response()->json("Not Implemented");
}
}

I know the question has already been answered and accepted, but I thought it a good idea to share something else and I cannot comment yet.
The unresponsive controller can also be caused when adding extra methods inside a resource controller, now there's not a problem in doing that, however.
If adding routes to your route file and you have a resource route setup for that controller, make sure you either:
A: Add the extra routes above the declaration of your resource route.
B: Use a two stroke approach i.e. task/ajax/getGoodStuff
This is because is you do a php artisan route:list you will notice your resource routes have (using the task controller as example):
task/{task} three time for methods head, patch and delete and
task/{task}/edit for editing a record.
Now this will only drive you crazy while the other methods are not completed, but it will drive you crazy at some point!

Related

Laravel Models/function, how to make a main "function"

So guy's, I've created a Laravel project.
I have a master. Layout which always contains the user data.
So I have a navbar with $user->name for example.
In every controller I needed to add the User model and also the where function.
$user = User::find(auth()->user()->id)
Maybe this example is bad, but I've also included the company in the master, so it shows in the Navbar.
Is there a way, that I don't need to repeat that process? So I don't need it always in the controller.
Thanks for reading.
In laravel you are extending each class from a main controller so its better to create a method in main class like this
child controller
class testController extends Controller
{
// as you can see its extending so go into Controller class
}
parent class, So here i have creatd a getName method here. If you want get the value through mode
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
private $current_user_name = 'test';
public function getName()
{
return ($this->current_user_name);
}
}
Now go back to child controller and pass this method in view
class testController extends Controller
{
public function index()
{
return view('', $data = ['name' => $this->getName()]);
}
}
Hope this cover your query. In this way you don't need to repeat your code in every controller.
You can get data in your blade template too, like user information, but if you need more complex data and you don't want to put logic in blade, you can use this method (AppServiceProvider.php):
public function boot()
{
view()->composer('your_mast_layout', function($view)
{
$data = ...
$view->with('variable_name', $data);
});
}

Laravel : Class controller does not exist

I have created a simple controller and define a function. But when i run this it returns an error that controller does not exist.
In my web.php assign a route.
<?php
Route::get('/', function () { return view('front.welcome'); });
Route::get('plan','PlanController#PlanActivity')->name('plan');
On otherside in my controller my code:
<?php
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller as BaseController;
use Illuminate\Http\Request;
class PlanController extends Controller {
public function PlanActivity()
{
dd("hello");
//return view('admin.index');
}
}
This controller created on App\Http\Controllers\Front - on front folder
Error :
ReflectionException (-1)
Class App\Http\Controllers\PlanController does not exist
Add Front part to:
Route::get('plan', 'Front\PlanController#PlanActivity')->name('plan');
Also, change the top of the controller to:
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
And run composer du.
From the docs:
By default, the RouteServiceProvider includes your route files within a namespace group, allowing you to register controller routes without specifying the full App\Http\Controllers namespace prefix. So, you only need to specify the portion of the namespace that comes after the base App\Http\Controllers namespace.
First when defining route, make sure to use the correct path for the controller. the correct is:
Route::get('plan','Front/PlanController#PlanActivity')->name('plan');
Second you have imported Controller Class as BaseController. so you should extends BaseController not Controller:
class PlanController extends BaseController {
public function PlanActivity()
{
dd("hello");
//return view('admin.index');
}
}

Dynamically hide Laravel barryvdh debugbar

I could not able to hide Laravel Debugbar dynamically, i.e on the run time. I have tried the following from parent Controller class constructor:
<?php
namespace App\Http\Controllers;
class Controller extends BaseController {
use AuthorizesRequests,
DispatchesJobs,
ValidatesRequests;
public $foo = 'null';
public function __construct() {
\Debugbar::disable();
// and also
config(['debugbar.enabled' => false]);
....
All of the above tries failed. I'd like to mention that controller is the parent controller of all other controllers' classes.
The only working way is not dynamic way, where I have to change configuration manually. I don't know why the override configurations doesn work as the documentation states?
Without seeing all you code, yours should work. Here is how I configure mine to work in a local environment and disable it with specific requests.
AppServiceProvider
use Barryvdh\Debugbar\ServiceProvider as DebugbarServiceProvider;
...
public function register()
{
if ($this->app->environment('local')) {
$this->app->register(DebugbarServiceProvider::class);
}
}
Where I would like to disable I put.
use Barryvdh\Debugbar\Facade as Debugbar;
...
if (App::environment('local')) {
Debugbar::disable();
}
Update per comment
Why do you put something in your routes file like this.
use Barryvdh\Debugbar\Facade as Debugbar;
...
Route::group(array('domain' => 'admin.example.com'), function()
{
Debugbar::disable();
});

Best way to define global variables from database in laravel

I want to define some variables from database to take them in any place of the app (controllers and views at least).
I found a way to do this in Http/Controllers/Controller.php:
namespace App\Http\Controllers;
use Session;
use Request;
use View;
use App\Http\Requests;
use Log;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct()
{
$this->middleware(function ($request, $next) {
$t = array();
$translations = \App\Translation::all();
foreach ($translations as $translation) {
$t[$translation->code] = $translation->text;
}
View::share('t', $t);
});
}
}
It works fine - I can access {{$t['something'}} in my app, but there is a problem with Auth route /register or /login, in these pages $t variable is not defined.
I think because Auth performs some actions before this my __construct, how to fix it?
Or maybe there is a better way to set dynamic variables from database reachable in all app views and controllers?
(laravel 5.3) I'm new to laravel, so can't feel the architecture yet.
I would go with setting a custom Config like this:
Config::set('translations', your_array_from_database);
You can even define your own helper function for fast retrieving, ie.
function t($name)
{
return Config::get('translations.'.$name);
You can set your own translations Config in a middleware, so you can decide the exact order in the request-response cycle you want to load it from database.
I haven't used Laravel for some time but my guess is, based on the 5.3 docs, is you can just call your middleware from those Auth controllers that are missing it. In the Auth Register controller you can add middleware, for example:
app/Http/Controllers/Auth/RegisterController.php
public function __construct()
{
$this->middleware('guest');
$this->middleware(function ($request, $next) {
// Add your middleware logic here
// or put it in it's own file and reference like 'guest' above.
return $next($request);
});
}
Try your logic directly in the closure above first. Then shift to its own class file and add it to the routeMiddleware array in the kernel.
Alternatively, you could include the middleware in your base controller you extend from: https://github.com/laravel/laravel/blob/5.3/app/Http/Controllers/Controller.php
Try using compact function in Laravel. Something like this:
//function to fetch data
//$t = \App\Translation::all();
return View::make('gameworlds.mygame', compact(['t']));
Then on the view you can access it like:
{{$t}}

Routing in Laravel is not working

I am using laravel 5.0
I am trying to route the following. But it is not working
Route::post('accesscontrols/permissions', 'AccescontrolsController#permission');
I don't know what error in this.
It does not access permissions function in AccesscontrolsController
I have a function in AccesscontrolsController
public function permission()
{
$roles = DB::table('roles')->get();
$permissions = DB::table('permissions')->get();
return view('accesscontrols.permission', compact('roles', 'permissions'));
}
What I have did wrong?
Your route declaration should be made in app/Http/routes.php.
Also, make sure that your controller is within the App\Http\Controllers namespace and that it extends App\Http\Controllers\Controller.
Ex:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function permission()
{
...
Also, if you whish to test it in the browser (by typing "accesscontrols/permissions" in the address bar), you route should answer to the GET verb. Try to declare it using Route::get( instead.
You are returning a view in your method and you are not working with any POST data, which is strange. Are you sure you want POST request and not GET?

Resources