this is my web route php:
Route::get('settings', 'Settings\SettingsController#edit')->name('admin.settings.edit');
and I call this route name like below:
<a href="{{ route('admin.settings.edit') }}" class="nav-link ">
<span class="title">Settings</span>
</a>
but I got this error:
Route [admin.settings.edit] not defined. (View:
C:\xampp7\htdocs\template\resources\views\layouts\admin\sidebar.blade.php)
(View:
C:\xampp7\htdocs\template\resources\views\layouts\admin\sidebar.blade.php)
(View:
C:\xampp7\htdocs\template\resources\views\layouts\admin\sidebar.blade.php)
rouet:list returns this error message: `Class App\Http\Controllers\Admin\Settings\SettingsController does not exist
but I have this controller:
namespace App\Http\Controllers\Admin\SettingsController;
use App\Http\Controllers\Controller;
use App\Shop\Brands\Repositories\BrandRepository;
use App\Shop\Brands\Repositories\BrandRepositoryInterface;
use App\Shop\Brands\Requests\CreateBrandRequest;
use App\Shop\Brands\Requests\UpdateBrandRequest;
class SettingsController extends Controller
{
public function __construct(){}
public function index()
{}
public function create(){}
public function store(){}
/**
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit()
{
dd("milad");
return view('admin.brands.edit', ['brand' => '']);
}
/**
* #param UpdateBrandRequest $request
* #param $id
*
* #return \Illuminate\Http\RedirectResponse
* #throws \App\Shop\Brands\Exceptions\UpdateDiscountCodesErrorException
*/
public function update(UpdateBrandRequest $request, $id)
{
// $brand = $this->brandRepo->findBrandById($id);
//
// $brandRepo = new BrandRepository($brand);
// $brandRepo->updateBrand($request->all());
//
// return redirect()->route('admin.brands.edit', $id)->with('message', 'Update successful!');
}
public function destroy()
{}
}
`
updated
all my web route php:
/**
* Admin routes
*/
Route::namespace('Admin')->group(function () {
Route::get('admin/login', 'LoginController#showLoginForm')->name('admin.login');
Route::post('admin/login', 'LoginController#login')->name('admin.login');
Route::get('admin/logout', 'LoginController#logout')->name('admin.logout');
});
Route::group(['prefix' => 'admin', 'middleware' => ['employee'], 'as' => 'admin.' ], function () {
Route::namespace('Admin')->group(function () {
Route::group(['middleware' => ['role:admin|superadmin|clerk, guard:employee']], function () {
Route::get('/', 'DashboardController#index')->name('dashboard');
Route::namespace('Products')->group(function () {
Route::resource('products', 'ProductController');
Route::get('remove-image-product', 'ProductController#removeImage')->name('product.remove.image');
Route::get('remove-image-thumb', 'ProductController#removeThumbnail')->name('product.remove.thumb');
});
Route::namespace('Customers')->group(function () {
Route::resource('customers', 'CustomerController');
Route::resource('customers.addresses', 'CustomerAddressController');
});
Route::namespace('Categories')->group(function () {
Route::resource('categories', 'CategoryController');
Route::get('remove-image-category', 'CategoryController#removeImage')->name('category.remove.image');
});
Route::namespace('Orders')->group(function () {
Route::resource('orders', 'OrderController');
Route::resource('order-statuses', 'OrderStatusController');
Route::get('orders/{id}/invoice', 'OrderController#generateInvoice')->name('orders.invoice.generate');
});
Route::resource('addresses', 'Addresses\AddressController');
Route::resource('countries', 'Countries\CountryController');
Route::resource('countries.provinces', 'Provinces\ProvinceController');
Route::resource('countries.provinces.cities', 'Cities\CityController');
Route::resource('couriers', 'Couriers\CourierController');
Route::resource('attributes', 'Attributes\AttributeController');
Route::resource('attributes.values', 'Attributes\AttributeValueController');
Route::resource('brands', 'Brands\BrandController');
Route::resource('discounts', 'DiscountCodes\DiscountCodesController');
Route::resource('comments', 'Comments\CommentsController');
Route::resource('messages', 'Messages\MessagesController');
Route::resource('pages', 'Pages\PagesController');
Route::resource('blog-categories', 'BlogCategories\BlogCategoriesController');
Route::resource('blog-posts', 'BlogPosts\BlogPostsController');
Route::resource('scores-categories', 'ScoresCategories\ScoresCategoriesController');
Route::resource('scores-levels', 'ScoresLevels\ScoresLevelsController');
Route::resource('affiliate-categories', 'AffiliateCategories\AffiliateCategoriesController');
Route::resource('products-codes', 'ProductsCodes\ProductsCodesController');
Route::get('settings', 'SettingsController#edit')->name('admin.settings.edit');
});
Your controller namespace is wrong.
namespace App\Http\Controllers\Admin\SettingsController;
Change it to:
namespace App\Http\Controllers\Admin\Settings;
and your route to:
Route::get('settings', 'Admin\Settings\SettingsController#edit')->name('admin.settings.edit');
Related
What I'm trying to do is group multiple prefixes with one middleware:
Route::group(['middleware' => ['centralize']], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setLocale()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCountry()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCity()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setArea()], function () {
//routes
});
});
});
});
});
I have added the centralize middleware to kernel:
protected $routeMiddleware = [
...
'centralize'=> \App\Http\Middleware\Centralize::class,
...
];
But the middleware is not being called at all, is there is something missing here?
EDIT: it goes directly to the view of the home, I am doing dd inside of the middleware but it never reaches there!
EDIT: middleware code:
<?php
namespace App\Http\Middleware;
use App\Utilities\Centralization;
use Closure;
use Illuminate\Http\RedirectResponse;
class Centralize
{
/**
* #var \Illuminate\Http\Request
*/
private $request;
/**
* #var array
*/
private $params;
private $location;
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(\Illuminate\Http\Request $request, Closure $next)
{
$this->request = $request;
dd('hit');
$this->params = explode('/', $request->getPathInfo());
$this->figureLocale();
$this->figureCountry();
$this->figureCity();
$this->figureArea();
$this->figureLocation();
$redirection = implode('/', $this->params);
if ($request->getPathInfo() !== $redirection) {
return new RedirectResponse($redirection, 302, ['Vary' => 'Accept-Language']);
}
\View::share([
'countries' => Centralization::getCountries(),
'cities' => Centralization::getCities(),
'areas' => Centralization::getAreas(),
'location' => $this->location
]);
return $next($request);
}
private function figureLocale()
{
//...
}
private function figureCountry()
{
//..
}
private function figureCity()
{
//...
}
private function figureArea()
{
//...
}
private function figureLocation()
{
//...
}
}
EDIT: I also have tried:
Route::middleware(['centralize'])->group(function () {
Route::group(['prefix' => \App\Utilities\Centralization::setLocale()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCountry()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCity()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setArea()], function () {
//..
});
});
});
});
});
But with the same result , it never hits the middleware!
EDIT: clearing cache using artisan and manual doesn't work either!
Group route middleware called like this:
In routes/web.php
Route::group(['middleware' => ['centralize']], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setLocale()], function () {
Route::group(['prefix' => \App\Utilities\Centralization::setCountry()], function () {
//routes
});
});
});
In app/Http/kernal.php
protected $routeMiddleware = [
'centralize' => \App\Http\Middleware\CentralizeMiddleware::class,
];
In app/Http/Middleware/CentralizeMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CentralizeMiddleware
{
public function handle($request, Closure $next)
{
if (//Your Condition) {
//If true
}
else {
return $next($request);
}
}
}
You mentioned in one edit that:
it goes directly to the view of the home
So the URL you are visiting is actually /. And as clarified in the comments, the "home" route was defined nested inside the prefixes. But that means it is really a route for something like /fr/france/paris/somewhere/, and not a route for /.
The prefix in the route means "this route applies to URIs with this prefix". If a URI does not include that prefix, this routing is not applied.
So that means there is no route for /, and visiting it will:
not fire the centralize middleware;
not find a matching route, so throw a 404;
If you want to apply your centralize middleware to your home route, you'll need to place it inside that group, but outside the prefixes:
Route::middleware(['centralize'])->group(function () {
Route::get('/', 'HomeController#index')->name('home');
Route::group(['prefix' => \App\Utilities\Centralization::setLocale()], function () {
// ...
});
});
I want to delete an item but I got this error message:
(1/1) MethodNotAllowedHttpException
in RouteCollection.php line 255
at RouteCollection->methodNotAllowed(array('PUT', 'DELETE'))
my routes:
Route::group(['prefix' => '/Seller', 'middleware' => ['seller_access']], function () {
Route::get('/','Seller\SellerController#index')->name('seller');
Route::group(['prefix' => '/Products'], function () {
Route::get('/', 'MarketingBundle\Seller\Product\ProductController#index')->name('marketing.seller.product.index');
Route::delete('/{id}', 'MarketingBundle\Seller\Product\ProductController#delete')->name('marketing.seller.product.delete');
Route::put('/{id}', 'MarketingBundle\Seller\Product\ProductController#update')->name('marketing.seller.product.update');
});
my url:
Seller/Products/228
my controller:
class ProductController extends Controller
{
public $resources = "marketing.seller.product";
public function index(Request $request)
{
$products = \Auth::user()->sellerProduct()->paginate(10);
return view($this->resources . '.index', [
'products' => $products
]);
}
/**
* #param $product_id
* #return \Illuminate\Http\JsonResponse
*/
public function delete($product_id)
{
dd("masoud");
\Auth::user()->sellerProduct()->detach(['product_id' => $product_id]);
return response()->json(['status' => true]);
}
re-order your routes like this.
Route::delete('/{id}', 'MarketingBundle\Seller\Product\ProductController#delete')->name('marketing.seller.product.delete');
Route::put('/{id}', 'MarketingBundle\Seller\Product\ProductController#update')->name('marketing.seller.product.update');
Route::get('/', 'MarketingBundle\Seller\Product\ProductController#index')->name('marketing.seller.product.index');
In order for laravel to know you're sending a patch or delete request you need to add a method field into your forms.
<form method='POST' action='#'>
#csrf
{{ method_field('PATCH') }}
</form>
Documentation
https://laravel.com/docs/5.7/helpers#method-method-field
https://laravel.com/docs/5.0/routing#method-spoofing
If i go to http://www.yourdomain.com/admin/login i see my login page.
If i go to http://www.yourdomain.com/admin/example i have the redirect to http://www.yourdomain.com/login without the admin.
My web routes:
Auth::routes();
Route::prefix('admin')->group(function() {
Route::get('/login','Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login','Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/manifiesto','AdminController#getIndex')->name('admin.dashboard');
Route::get('/logout','Auth\AdminLoginController#logout')->name('admin.logout');
Route::get('/trabajadores','AdminController#showTrabajadores')->name('admin.trabajadores');
Route::get('/clientes','AdminController#showClientes')->name('admin.clientes');
Route::get('/proyectos','AdminController#showProyectos')->name('admin.proyectos');
Route::get('/administradores','AdminController#showAdmins')->name('admin.administradores');
});
When i put some url with the /admin before and user isn't logged, i want to redirect to /admin/login.
Thanks.
More info:
App/http/Controllers/Auth/AdminLoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
class AdminLoginController extends Controller
{
protected $loginPath = 'admin/login';
public function __construct()
{
$this->middleware('guest:admin', ['except' => ['logout']]);
}
public function showLoginForm()
{
return view('backend.public.pages.login');
}
public function login(Request $request)
{
//validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
//attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
//if successful, then redirect to their intended location
return redirect()->intended(route('admin.dashboard'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
public function logout()
{
Auth::guard('admin')->logout();
return redirect('/');
}
}
App\Http\Middleware\AdminAuthenticate.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AdminAuthenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('admin/login'); // <--- here
}
}
return $next($request);
}
}
Create an middleware
php artisan make:middleware AuthAdmin
Check for guest in the handle method of the middleware
public function handle($request, Closure $next)
{
if (Auth::guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('admin/login');
}
}
return $next($request);
}
Add a key to the middleware in app/Http/Kernel.php in $routeMiddleware array
'auth_admin' => \App\Http\Middleware\AuthAdmin::class
Attach the auth_admin middleware to the group
Route::group(['prefix' => 'admin', 'middleware' => 'auth_admin'], function() {
// Your admin routes except login
});
write bellow code in your route.php file
Route::group(array('prefix' => 'admin'), function() {
Route::controller('login', 'AdminloginController');
});
Route::group(array('before' => 'admin_ajax', 'prefix' => 'admin'), function()
{
//route for pages which are render after login
});
Route::get('/admin', function() {
return View::make('admin.loginform');
});
And Write bellow code in your filter.php file
Route::filter('admin_ajax', function() {
if (!Auth::admin()->check()) {
return Redirect::to('admin/login');
} else {
}
});
And if you are using laravel 5.4
Route::get('/manage', function () {
return redirect('manage/login');
});
Route::group(['prefix' => 'manage'], function() {
//login bypass for the below listed controllers
Route::resource('login', 'AdminLoginController#showLoginForm');
Route::post('dologin', 'AdminLoginController#login');
});
All you can do is add the auth middleware like this :
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
Route::get('/login','Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login','Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/manifiesto','AdminController#getIndex')->name('admin.dashboard');
Route::get('/logout','Auth\AdminLoginController#logout')->name('admin.logout');
Route::get('/trabajadores','AdminController#showTrabajadores')->name('admin.trabajadores');
Route::get('/clientes','AdminController#showClientes')->name('admin.clientes');
Route::get('/proyectos','AdminController#showProyectos')->name('admin.proyectos');
Route::get('/administradores','AdminController#showAdmins')->name('admin.administradores');
});
But by default this will redirect to /login, if you want to override this you have two chocies depending on if you have other type of users that uses the /login route or not !!
If NO ONE uses /login route
1- You need to modify App\Http\Middleware\Authenticate::handle() method and change /login to admin/login.
2- Then you need to add $loginPath property to your \App\Http\Controllers\Auth\AuthController class.
Authenticate
namespace App\Http\Middleware;
class Authenticate {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('admin/login'); // <--- here
}
}
return $next($request);
}
}
AuthController
namespace App\Http\Controllers\Auth;
class AuthController extends Controller
{
protected $loginPath = 'admin/login'; // <--- here
// ... other properties, constructor, traits, etc
}
If there is someone using /login route
You must create you own middleware and do what it takes for auth checking in the handle method with redirecting to your admin/liging route :)
In this case :
Add the following line in $routeMiddleware property at app/Http/Kernel.php file
'adminAuth' => \App\Http\Middleware\YourNewMiddleware::class,
Don't forget to add your new middleware in route group as follow
Route::group(['prefix' => 'admin', 'middleware' => 'adminAuth'], function()
{
// your admin routes
});
Make an another middleware for admin. follow the step
Make a file named AdminAuthenticate in app/Http/Middleware location and copy the content of Authenticate in New file
change the Class name as AdminAuthenticate
Change the content of handle function as show below
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/admin/login');
}
}
return $next($request);
}
Add the following line in $routeMiddleware array at app/Http/Kernel.php file
'AdminAuth' => \App\Http\Middleware\AdminAuthenticate::class,
Now everything is okay. just add your new middleware in route group as follow
Route::group(['prefix' => 'admin', 'middleware' => 'AdminAuth'], function()
{
// all admin routes
});
Or you can add new middleware to constructor function of every admin controller as like below
$this->middleware('AdminAuth');
I have a problem that I can not resolve in Laravel 5.4.
I'm using the Postman extension to make requests for my API, so far it works normally with GET, but when I try to do a POST, the method that's actually called is GET again. (The API can not have authentication or token for the user).
api.php:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['api' => ['auth:api']], function(){
Route::group(['prefix' => 'user'], function(){
Route::get('{id}', ['uses' => 'UserController#getUser']);
Route::post('', ['uses' => 'UserController#saveUser']);
Route::get('', ['uses' => 'UserController#allUsers']);
Route::put('{id}',['uses' => 'UserController#updateUser']);
Route::delete('{id}', ['uses' => 'UserController#deleteUser']);
});
});
UserController.php:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller{
protected $user = null;
public function __construct(User $user){
$this->user = $user;
}
public function allUsers(){
return $this->user->allUsers();
}
public function getUser($id){
}
public function saveUser(){
return $this->user->saveUser();
}
public function updateUser($id){
}
public function deleteUser($id){
}
}
User.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $hidden = ['venda','remember_token', 'created_at','updated_at'];
public $fillable = ['nome','email', 'venda'];
public function allUsers(){
return self::all();
}
public function saveUser(){
$input = Input::all();
echo 'aa';
$user = new User();
$user->fill($input);
$user->save();
return $user;
}
}
First change this:
Route::group(['api' => ['auth:api']], function(){
To:
Route::group(['middleware' => ['auth:api']], function(){
So i have a 'TicketController' which holds my functions for manipulating 'tickets' in a system.
I am looking to work out the best way to send my new route that will take a route parameter of {id} to my TicketController to view a ticket.
Here is my route set
Route::group(['middleware' => 'auth', 'prefix' => 'tickets'], function(){
Route::get('/', 'TicketController#userGetTicketsIndex');
Route::get('/new', function(){
return view('tickets.new');
});
Route::post('/new/post', 'TicketController#addNewTicket');
Route::get('/new/post', function(){
return view('tickets.new');
});
Route::get('/view/{id}', function($id){
// I would like to ideally call my TicketController here
});
});
Here is my ticket controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Ticket;
use App\User;
class TicketController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Returns active tickets for the currently logged in user
* #return \Illuminate\Http\Response
*/
public function userGetTicketsIndex()
{
$currentuser = \Auth::id();
$tickets = Ticket::where('user_id', $currentuser)
->orderBy('updated_at', 'desc')
->paginate(10);
return view('tickets.index')->with('tickets', $tickets);
}
public function userGetTicketActiveAmount()
{
$currentuser = \Auth::id();
}
public function addNewTicket(Request $request)
{
$this->validate($request,[
'Subject' => 'required|max:255',
'Message' => 'required|max:1000',
]);
$currentuser = \Auth::id();
$ticket = new Ticket;
$ticket->user_id = $currentuser;
$ticket->subject = $request->Subject;
$ticket->comment = $request->Message;
$ticket->status = '1';
$ticket->save();
}
public function viewTicketDetails()
{
//retrieve ticket details here
{
}
You don't need to use closure here. Just call an action:
Route::get('/view/{id}', 'TicketController#showTicket');
And in TicketController you'll get ID:
public function showTicket($id)
{
dd($id);
}
More about this here.
You should use type-hint in laravel. Its awesome
In route
Route::get('/view/{ticket}', 'TicketController#viewTicketDetails');
In controller
public function viewTicketDetails(Ticket $ticket)
{
//$ticket is instance of Ticket Model with given ID
//And you don't need to $ticket = Ticket::find($id) anymore
{