Is it possible to use prefix as param ir Laravel routes? - laravel

I have different languages on the page and I'm wondering is it possible to use them as prefix param. Something like this:
Route::group(['prefix' => '{lang}'], function() {
Route::get('/', 'BlogController#posts');
})->where('lang', '(en|fr|de)');

The closest i could think of was this:
Route::group(['prefix' => '{lang}'], function() {
Route::get('/', 'BlogController#posts')->where('lang', '(en|fr|de)');
});

This code get language from your languages table. Hope you can change this code to your requirements, if not - ask ;) try to help you..
Model
class Language() {
public $table = 'languages';
public $timestamps = false;
public function set() {
$code = Request::segment(1);
$language = Language::whereCode($code)->first();
return $language;
}
Router
$language = new Language();
$language->set();
Route::get('/', function() use ($language) {
return Redirect::to('/' . $language->code);
});
Route::group(array('prefix' => $language->code), function() {
Route::get('/', array('as' => 'home', 'uses' => 'PageController#index'));
});

Related

How make Route::resource with page and filter options?

In Laravel 5.8 making backend rest api app with resource defined in routes/api.php, as
Route::group(['middleware' => 'jwt.auth', 'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {
...
Route::resource('skills', 'API\Admin\SkillController');
now on clients part for listing of skills I need to add current_page and filter_name.
Can it be done with Route::resource definition ?
Actually when we making the resource controller in laravel then it created the method index
create,
store,
show,
edit,
update,
destroy.
method and routes of these respectively but when you are going to define the new method and for access this method then you need to create new route for this.
otherwise it is not possible with the resource route in laravel.
public function abc(Request $request)
{
dd($request->all());
}
route for this
route::post('/abc','ABCController#abc')->name('abc');
you can check the route by this command
php artisan route:list or
php artisan r:l
hope you understand.
After some search I found a decision in defining in routes one more post route:
Route::group(['middleware' => 'jwt.auth', 'prefix' => 'adminarea', 'as' => 'adminarea.'], function ($router) {
Route::post('skills-filter', 'API\Admin\SkillController#filter');
Route::resource('skills', 'API\Admin\SkillController');
...
and in app/Http/Controllers/API/Admin/SkillController.php :
<?php
namespace App\Http\Controllers\API\Admin;
use Auth;
use DB;
use Validator;
use App\User;
use App\Http\Resources\Admin\Skill as SkillResource;
class SkillController extends Controller
{
private $requestData;
private $page;
private $filter_name;
private $order_by;
private $order_direction;
public function __construct()
{
$this->middleware('jwt.auth', ['except' => []]);
$request = request();
$this->requestData = $request->all();
}
public function filter()
{
if ( ! $this->checkUsersGroups([ACCESS_ROLE_ADMIN])) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$backend_items_per_page = Settings::getValue('backend_items_per_page');
$this->page = !empty($this->requestData['page']) ? $this->requestData['page'] : '';
$this->filter_name = !empty($this->requestData['filter_name']) ? $this->requestData['filter_name'] : '';
$this->order_by = !empty($this->requestData['order_by']) ? $this->requestData['order_by'] : 'name';
$this->order_direction = !empty($this->requestData['order_direction']) ? $this->requestData['order_direction'] : 'asc';
$this->index();
$skills = Skill
::getByName($this->filter_name)
->orderBy($this->order_by, $this->order_direction)
->paginate($backend_items_per_page);
return SkillResource::collection($skills);
} // public function filter()
public function index()
{
if ( ! $this->checkUsersGroups([ACCESS_ROLE_ADMIN])) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$backend_items_per_page = Settings::getValue('backend_items_per_page');
$skills = Skill::paginate($backend_items_per_page);
return SkillResource::collection($skills);
}
As that is adminarea some filter actions can have more 1 filter...
Just interested to know which other decisions are possible here?

Laravel 5.5 administrator route issue

I have the below mentioned route:
Route::get('/', 'HomeController#index');
Route::get('administrator', array('before' => 'auth', 'uses' => 'Administrator\IndexController#index'));
//Route::get('/administrator', 'Administrator\IndexController#index');
Route::group(['prefix' => 'administrator'], function() {
Route::get('login', 'Administrator\IndexController#index')->name('login');
Route::post('login', 'Auth\LoginController#doLogin');
Route::get('logout', 'Auth\LoginController#logout');
});
My intention is when someone try to access http://127.0.0.1:8000/administrator/ this will go directly to the login page of the administrator.
However, when I tried to access the same, it said 404 not found.
IndexController under Administrator folder is looks below:
class IndexController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('guest')->except('doLogout');
}
public function index() {
//$session = session()->all();
if(Auth::check() == 1){
return Redirect::intended('/administrator/dashboard')->with('successMessage', 'You have successfully logged in.');
}
//print_r($session);
//echo $session['_token'];
//if($session['_token'] == '')
$data = array();
$data['title'] = "Shop To My Door - Administrator Panel";
return view('Administrator.index.index', $data);
}
}
You have route and group with the same name "administrator"
My suggestion for routing:
Route::get('/', 'HomeController#index');
Route::group(['prefix' => 'administrator'], function() {
Route::get('/', 'Administrator\IndexController#index');
Route::get('login', 'Administrator\IndexController#login');
Route::post('login', 'Auth\LoginController#doLogin');
Route::get('logout', 'Auth\LoginController#logout');
});

Laravel : How to define route start with prefix # like medium.com/#{username}?

How to define route in laravel , which start with prefix # in web.php
like myapp.com/#username
use route group() to define prefix as -
Route::group(['prefix' => '#username'], function () {
Route::get('/','TestController#test');
});
You can access this url as www.base_url.com/#username/
If you want to set username dynamically then you could this-
Route::group(['prefix' => '#{username}'], function () {
Route::get('/','TestController#test');
});
And in your controller-
public function test($username)
{
echo $username;
}
I have got my answer .
Route::group(['namespace' => 'User','prefix' => '#{username}'],
function () {
Route::get('/','UserController#get_user_profile');
});
in User Controller
public function get_user_profile($username){
$user=User::where('slug',$username)->first();
return response()->json($user);
}

Laravel (5.4) passport routes with current user that also works if not logged in

I'm trying to make one route in laravel which can have a user if it is logged-in but can still work if not.
In my case I have a table called "venues" and a "user" that can have a venue as his favourite.
So these are my routes:
Route::group(['middleware' => ['cors', 'bindings', 'auth:api']], function () {
Route::match(['GET', 'OPTIONS'], 'venue/{venue}', 'VenuesController#getVenue')->name('venue')->where('venue', '[0-9]+');
});
Route::group(['middleware' => ['cors', 'bindings', 'api'], 'namespace' => 'Api'], function () {
Route::match(['GET', 'OPTIONS'], 'venue/{venue}', 'VenuesController#getVenue')->name('venue')->where('venue', '[0-9]+');
});
Now I noticed that Auth::user(); is only available in the route with the middleware with 'auth:api' but I also want it to get the venue if the user is not logged in. And using both groups doesn't work this way.
My Venue model looks like this:
class Venue extends Model
{
protected $appends = [
'favourite',
];
public function users()
{
return $this->belongsToMany('App\Models\User', 'venue_user');
}
public function getFavouriteAttribute()
{
$user = Auth::user();
$isFav = false;
if ($user) {
if ($user->venues) {
foreach ($user->venues as $item) {
if ($item->id === $this->id) {
$isFav = true;
}
}
}
}
return $isFav;
}
}
There must be a better way to do this.
I hope someone can help me out.
Ok I finally found the answer to my own question.
Apparently the right way to get the current of Passport is by doing:
$user = auth()->guard('api')->user();
Auth::user() is only available in routes with a middlewhere of 'auth:api' but this one is available everywhere if I say so correctly.
Feel free to correct me if I'm wrong :)

How can I redirect a route using laravel?

I use group to help visualize my project's routes.php, now the problem is
for example, when a user access to "/dir", I want to make it be redirected to "/dir/ele"
Route::group(['prefix' => 'dir'], function () {
Route::group(['prefix' => 'ele'], function () {
Route::controller('/', 'dir\eleController');
});
Redirect::route('ele');
}
Why is this not working?
The route dir/ele is going to a controller, but you are doing the redirect in your routes.php instead of in the controller.
You should use a closure route and do everything in the routes.php or use a controller and move the redirect to the controller:
Closure route in routes.php:
Route::group(['prefix' => 'dir'], function () {
Route::group(['prefix' => 'ele'], function () {
Route::get('/', function() {
return Redirect::to('ele');
});
});
});
Which can be simplified to:
Route::group(['prefix' => 'dir'], function () {
Route::get('ele', function(){
return Redirect::to('ele');
});
});
Or use the controller way:
Routes.php
Route::group(['prefix' => 'dir'], function () {
Route::group(['prefix' => 'ele'], function () {
Route::controller('/', 'eleController#redirect');
});
}
eleController.php
class eleController extends BaseController {
function redirect() {
return Redirect::to('ele');
}
}

Resources