I have a route group with this structure:
Route::prefix('admin/{w_id}')->middleware(['auth'])->as('weblog.')->group(function () {
Route::get('/dashboard', [HomePageController::class, 'index'])->name('dashboard');
Route::resource('/blogcategory', CategoryController::class);
});
On dashboard route I have w_id in url and when I want to redirect user to blogcategory route (from anywhere) I should pass w_id manully in route helper class, I need some thing to set in globally from current link.
For example when I using this method:
'route' => 'weblog.blogcategory.store'
I got error like :
Missing required parameters for [Route: weblog.blogcategory.store]
And I should pass w_id parameter to all route helper manually, I need set globally w_id from current url of page.
I'm developing fully separated admin area for user's weblog and weblog id is exist in all url.
In order to avoid passing w_id again you will need to use URL::defaults(), it will create a default value for your parameter.
You can use a middleware to pass the default value.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\URL;
class SetDefaultWidForWeblogs
{
public function handle($request, Closure $next)
{
URL::defaults(['w_id' => /* pass the default value here*/]);
return $next($request);
}
}
Now register the middleware in app/Http/Kernel.php class (See more description here)
protected $routeMiddleware = [
...
'pass_wid' => \App\Http\Middleware\SetDefaultWidForWeblogs::class,
];
Then use that middleware
So for your route group
Route::prefix('admin/{w_id}')->middleware(['auth', 'pass_wid'])->as('weblog.')->group(function () {
Route::get('/dashboard', [HomePageController::class, 'index'])->name('dashboard');
Route::resource('/blogcategory', CategoryController::class);
});
See in docs about default values to Url
Related
My routes:
Route::apiResource('courses', 'CourseController');
Route::apiResource('courses.classrooms', 'ClassroomController');
List: php artisan route:list
api/v1/courses/{course}
api/v1/courses/{course}/classrooms/{classroom}
My question is: all my functions in classroom controller needs the course, something like that
public function index($course_id)
{
$classroom = Classroom::where('course_id', $course_id)->get();
return $classroom;
}
public function store($course_id, Request $request)
{
// ...
$classroom->course_id = $course_id;
// ...
}
public function show($course_id, $id)
{
$classroom = Classroom::where('course_id', $course_id)->find($id);
return $classroom;
}
// ...
Have some Policy/Helper in Laravel to accomplish this automatically?
I believe it's not necessary to add the property $course_id in all functions manually, what can I do?
You can use a group to enclose all your routes. Something like:
Route::group(['prefix' => '{course}'], function () {
// you can place your routes here
});
So all the routes that exist in that group will already have the course value in the url path and you don't have to "rewrite it" for every route.
If that field is set by you for example an env variable then inside your RouteServiceProvider you can put the prefix you want in the mapApiRoutes function.
protected function mapApiRoutes()
{
Route::prefix('/api/v1/courses/'.config('app.myVariable'))
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
That way ALL your api endpoints will start with that prefix and you can have it in all the endpoints.
If the routes are registered correctly like you posted, your methods in the ClassroomsController should receive an additional parameter that's the course id fragment from the url.
For example if you request /api/v1/courses/1/classrooms route, the controller will receive the correct {course} parameter set to 1 as the first parameter.
You could then implement the index method of the ClassroomsController to use implicit model binding and get the Course instance with the given url id for the course.
To do so you have to type-hint the Course model for the first function's parameter and name the variable as the url fragment you want to use to retrive your model.
In your code example, you should do:
public function index(Course $course)
{
return $course->classrooms;
}
Note: I assume you have a relationship between Course and Classroom models to retrive the classrooms from the course model instance
You can read more about that on the official documentation here
Assume the following routes in a Laravel 5.5 API:
// custom routes for THIS user (the user making the request)
Route::get('/user', 'UserController#show');
Route::get('/user/edit', 'UserController#edit');
// register CRUDdy resource routes for users
Route::resource('users', 'UserController');
Let's use edit as the example:
public function edit(User $user)
{
...
}
As you can see, the edit route contains a type-hinted $user parameter. This works just fine for the users/13/edit route, as expected. However, I'd to configure the route /user/edit to pass along the $request->user() user object to the function. I don't want to check for the user object in the actual edit method as that could interfere with other validation (for instance, I don't want to default to the current user if someone passes a non-existent user ID, I want to return an error in that case).
In short: how can I register a route to first create a parameter, then pass it to the given controller method? My first thought was to use a closure:
Route::get('/user/edit', function(Request $request){
$user = $request->user();
});
But once inside the closure, I'm not certain how to then carry the request forward to the appropriate controller method.
Instead of a closure, you could make a new controller method that calls edit with the current user.
Let's say your route is this:
Route::get('/user/edit', 'UserController#editSelf');
Then in your controller:
public function editSelf(Request $request)
{
$this->edit($request->user());
}
I am new in Laravel.
routes/api.php I have written this function
Route::group(['namespace' => "Catalogue"],function(){
Route::resource('product','Product');
});
I have created a resource controller:
app/Controllers/Catalogue/Product.php
This is my index method:
public function index()
{
$pdo = DB::select('select count(*) from offers');
return $pdo;
}
I am trying to get the result from index method from url:
http://localhost:8000/api/Catalogue/product
However, this results in 404 not found.
Note: There is no issue in this part of url http://localhost:8000/api
Based on your route the link generated is http://localhost:8000/api/product
If you need the link to be http://localhost:8000/api/Catalogue/product , then add the prefix to the group.
Route::group(['prefix' => 'Catalogue', 'namespace' => 'Catalogue'], function() {
Route::resource('product', 'Product');
});
The namespace only sets the default namespace for the controller. The prefix sets the route prefix for all the routes in the group.
You are hitting the wrong uri.
Check http://localhost:8000/api/product
The namespace in the group route means you are assigning a namespace to a group of controllers. As you can see here https://laravel.com/docs/5.4/routing#route-group-namespaces. It has nothing to do with the routes.
Here you can see the other routes when you make them in the controller.
https://laravel.com/docs/5.4/controllers#controllers-and-namespaces
I've simple middleware which checks if there is a key in user session.
<?php
namespace App\Http\Middleware;
use Closure;
class CustomAuth
{
public function handle($request, Closure $next)
{
if($request->session()->has('uid')){
return $next($request);
}
else{
return view('unauth');
}
}
}
The problem is that I always get "Session store not set on request." error. Here is my route:
Route::get('home', function () {
return view('home');
})->middleware('web', 'CustomAuth');
I've added the middleware in app\Http\Kernel.php in the variable $middleware
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\CustomAuth::class
];
I also tried changing my route to this:
Route::group(['middleware' => ['web']], function () {
Route::get('home', function () {
return view('home');
})->middleware('CustomAuth');
});
But this didn't work. Any idea how I can make sure that the session had started, or start it before the middleware is called? I'm using Laravel 5.3
The L5 middleware consists of 3 "types".
The configuration is found in the Kernel.php file for HTTP requests (typically App\Http\Kernel. There's global middleware which will run for all requests and is declared in $middleware, there's the route group middleware which will run for all requests for a given route group and is declared in $middlewareGroups, by default all routes declared in web.php are considered to be web routes so all the web middleware apply.
The 3rd type is route middleware. These are declared in the $routeMiddleware array in the form "middlewareName" => Middleware::class and can be used in any route e.g.
Route::get("/route", function () { /* route body */ })->middleware("middlewareName");
These run in order global > group > route middleware and the SessionStart middleware runs as part of the group middleware. Any other middleware that needs access to the session will need to be placed after the SessionStart middleware.
Clarification
It occurs to be when re-reading this that this implies that you need to declare the middleware in the $middeware variable to use them. This is not the case, the following syntax is also allowed:
Route::get("/route", function () {
/* route body */
})->middleware(Middleware::class);
However this syntax will not allow you to provide parameters to the middleware when you use them as you would for example with the authentication middleware when you do auth:api (where api would be a parameter passed to the middleware).
I am using code that is below for admin routing in laravel.
Route::group(['prefix' => 'admin'], function() {
Route::get('/', 'Admin\AdminController#home');
Route::get('/users/userList', 'Admin\UserController#userList');
Route::get('/users/detail', 'Admin\UserController#detail');
Route::get('/posts/view', 'Admin\PostController#view');
Route::get('/posts/edit', 'Admin\PostController#edit');
Route::get('/posts/add', 'Admin\PostController#add');
});
This is working fine for me. But when I add new functions in code for that I have to write routing in routes file. For example: If I want to add edit functionality in users controller, for that I have to add new route like .
Route::get('/users/edit', 'Admin\UserController#edit');
So I have to add routing for each function.
I want to know How to use wild card for admin routing so that I have to write routing only for controller not for each function for example.
Route::group(['prefix' => 'admin'], function() {
Route::get('/', 'Admin\AdminController#home');
Route::get('/users/:any', 'Admin\UserController#:any');
Route::get('/posts/:any', 'Admin\PostsController#:any');
});
wild card replace the function name, and auto ridirect to that function.
You could use implicit controllers that will do what you need.
First declare a route for your implicit controller
Route::controller('users', 'UserController');
Then, on your controller, you have to follow a convention for naming your routes with HTTP verbs used to access them (get for GET, post for POST, any for both)
class UserController extends Controller {
public function getIndex()
{
//
}
public function postProfile()
{
//
}
public function anyLogin()
{
//
}
}
A note about composed method name from documentation
If your controller action contains multiple words, you may access the action using "dash" syntax in the URI. For example, the following controller action on our UserController would respond to the users/admin-profile URI:
public function getAdminProfile() {}