Laravel 5.1 Module with multiple controllers - laravel

I want to create module with number of controller like
Admin is Module name and have AdminController.
Admin module has another controller CategoryController, ProductController.
Now i wanted to use that controller as part of admin module How can i achive that using Artem-Schander/L5Modular

You have the wrong namespace in your CategoryController.php
It should be namespace App\Modules\Admin\Controllers
and not namespace App\Modules\Admin\Controllers\Category
working example:
routes.php:
Route::group(array('module' => 'Admin', 'namespace' => 'App\Modules\Admin\Controllers'), function() {
Route::resource('admin', 'AdminController');
Route::resource('category', 'CategoryController');
});
AdminController.php:
<?php namespace App\Modules\Admin\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Admin\Models\Admin;
class AdminController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
die('admin controller');
}
}
CategoryController.php:
<?php namespace App\Modules\Admin\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
//use App\Modules\Admin\Models\Admin;
class CategoryController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
die('category controller');
}
}
Here you said, you have a blank page. Check your .env file for the debug option and set it to true. Than you should have a detailed debug output.

Related

Problem with Route::apiResource() Laravel Framework 8.64.0

I'm using laravel 8 (Laravel Framework 8.64.0) to create an API. But when make a call to an endpoint, which i define with Route::apiResource it doesn't return the result from a query, returns nothing.
routes\api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\TodoController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
//Route::get('/todos', [TodoController::class, 'index']);
Route::apiResources([
'todos' => TodoController::class,
]);
Models\Todo.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'is_done',
'due_at',
'completed_at',
];
}
Controllers\TodoController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Todo;
class TodoController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return Todo::all();
}
If I add another route:
Route::get('/todos', [TodoController::class, 'index']);
and I call it, it works.
What could possible be the problem?
You may want to try create TodoResource class extend JsonResource by running
php artisan make:resource TodoResource
then inside Todo Controller index function, replace return Todo::all(); with
return TodoResource::collection(Todo::all());
Solution why not work, remove line from
routes\api.php:
use App\Http\Controllers\Api\TodoController;

How to share one method to all controllers in Laravel?

How to share one method to all controllers with different DI, view and parameters? I need something like this:
public function method(Model $model)
{
$baseData = [
'model' => $model,
'route' => route('$route', [$param => $model]),
];
return view($view);
}
All controllers extend App\Http\Controllers\Controller so you can just place it there
<?php
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function method(Model $model, $route, $param, $view)
{
// Declared but not used
$baseData = [
'model' => $model,
'route' => route($route, [$param => $model]),
];
return view($view);
}
}
And use it with $this->method()
For example in HomeController
<?php
namespace App\Http\Controllers;
use App\User;
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$user = User::first();
return $this->method($user, 'home', 'user', 'welcome');
}
}
Now accessing domain.tld/home will return the welcome view
If you want to share function to all controller best way will make service in service folder of app.
step to make service:-
1.create service using artisan command
php artisan make:service service_name and define function that to share to all controller in your project.
after making service your have to register this service with provider.make a provider using artisan command.
php artisan make provider:provider_name and you will see 2 function register and boot
register function is used to register your created service and boot for call already register service
register service like this
public function register()
{
$this->app->bind('App\Services\servicename', function( $app ){
return new serviceclassname;
});
}
3.Go config folder ,open app.php where you will get providers array. In this provider you have to define you provider like App\Providers\providerclassname::class,
call this service in controllers like use App\Services\serviceclassname;
public function functionname(serviceclassname serviceobject)
{
serviceobject->functionname();
}

Laravel: a simple MVC example

I'm new to Laravel and the documentation's basic task list returns Views from the Route(web.php) but I want to use a Controller to return an image file.
So I have for my route:
Route::get('/products', 'ProductController#index');
Then my ProductController action (please ignore comments as I'm using index to simplify things):
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
#return \Illuminate\Http\Response
Fetch and return all product records.
*/
public function index()
{
//
//return response()->json(Product::all(), 200);
return view('/pages/product', compact('product'));
}
And my product.blade.php (nested in views/pages/product):
<img src="/images/product/Frozen_Ophelia_800x.png">
I keep getting a ReflectionException Class App\Product does not exist.
I got this working when I just returned a view from the route. I'm getting a ReflectionException
Class App\Product does not exist so I think it's something at the top, ie. use App\Product; that is wrong.
Edit (below is my App\Product nested in app/Providers):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
//
use SoftDeletes
protected $fillable = [
'name', 'price', 'units', 'description', 'image'
];
public function orders(){
return $this->hasMany(Order::class);
}
}
Assuming App\Product model exists, correct code should be:
public function index() {
$product = Product::all();
return view('pages.product', compact('product'));
}
Check the docs.
PS did you call a $ composer dumpautoload? ReflectionException Class error is often related to new class autoloading (eg. new classes in a packages)
view function should have any view template not any url or route. Of you have file views/pages/product.blade.php then use
view('pages.product',compact('product'));

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');
}
}

Laravel5 won't match route edit_user/{id}

please, could you help me a bit?
I have this route in Laravel5:
Route::get('edit_user/{userId}', [
'as' => 'editUser',
'uses' => 'Auth\UserController#editUser'
]);
But when I try to go onto url .../edit_user/19 it wont match and redirect me into /home url...
Anyway, when I use this:
Route::get('edit_user/{userId}', [
'as' => 'editUser',
function($userId) {
die($userId);
}
]);
It returns 19.
Here is also my function:
public function editUser($userId) {
die($userId);
}
Here is also part of my controller:
<?php namespace App\Http\Controllers\Auth;
use App\Models\User;
use Auth;
use Hash;
use Mail;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class UserController extends Controller {
/**
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
*
* show edit user form
*
* #param $id
*/
public function editUser($userId) {
die($userId);
}
Do you know any idea, where might be problem?
Thank you very much for your opinions.
EDIT:
I find out solution -> need to edit exception to auth in __construct.
This should work with the code provided.
Check the following items:
1. Do you have this code in the __construct of your UsersController?
public function __construct()
{
$this->middleware('auth');
}
If so, you need to be lagged in to edit the user.
2. Is there any route listed before edit_user/{userId} that would override this route.
Try moving it to be the very first route.
3. Is you UserController namespaced properly?
<?php
namespace App\Http\Controllers\Auth;

Resources