Laravel 8 get only api route names - laravel

I want to get only API route names. How can I get all my route names inside of my api.php ?
I'm trying the code below but it lists all the routes of my app.
Route::getRoutes();
I'm waiting for your help

One way to determine is by checking the prefix:
$apiRoutes = collect();
$apiRoutesNames = [];
foreach (\Route::getRoutes() as $route) {
if ($route->action['prefix'] !== 'api') {
continue;
}
$apiRoutes->push($route);
$apiRoutesNames[] = $route->action['as'];
}
$apiRoutesNames = array_filter($apiRoutesNames);
This will work if you did not change the prefix in app/Providers/RouteServiceProvider.php

I had similar issue and clean Laravel 9.
There are few ways to do that, you may get all contents of the api.php, or directly get all information from your RouteServiceProvider.php.
I changed my RouteServiceProvider.php
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* #var string
*/
public const HOME = '/dashboard';
public const API_PREFIX = '/api'; // I added this line
and changed boot method to this:
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix(self::API_PREFIX) // to make it dynamic
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
After that this code should give you all the api routes:
use Illuminate\Support\Facades\Route;
collect(Route::getRoutes())->filter(function ($route){
return $route->action['prefix'] === RouteServiceProvider::API_PREFIX;
});
Or you can use Str::startsWith
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
collect(Route::getRoutes())->filter(function ($route){
return Str::startsWith($route->action['prefix'], RouteServiceProvider::API_PREFIX);
});
You can get all the information from the routes.

Related

How to Prevent Other User Access based on Authentication and User ID in Laravel 7

I have an ongoing Laravel project and I'm currently learning. So there will be multiple users that can register for the system. For example, user1 created an account and made transactions and changes on his account. When user2 register and login, user2 sees everything in user1's account instead of a fresh blank dashboard to get started with. I tried adding middleware->('auth'); in my routes but it didn't change anything.
HomeController
<?php
namespace App\Http\Controllers;
use App\MoneyTrade;
use App\MoneyTradeDeposit;
use App\Withdrawal;
use Illuminate\Http\Request;
use Laravel\Ui\Presets\Vue;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$moneytrades = MoneyTrade::all();
$moneytradeDeposits = MoneyTradeDeposit::all();
$amountSum = MoneyTradeDeposit::sum('amount');
$balance = Withdrawal::sum('amount');
return view('dashboard', compact('moneytrades', 'moneytradeDeposits', 'amountSum', 'balance'));
}
public function dashboard()
{
$moneytrades = MoneyTrade::all();
$moneytradeDeposits = MoneyTradeDeposit::all();
$amountSum = MoneyTradeDeposit::sum('amount');
$withdrawal = Withdrawal::all();
$balance = Withdrawal::sum('amount');
return view('dashboard', compact('moneytrades', 'moneytradeDeposits', 'amountSum',
'withdrawal', 'balance'));
}
public function stocks()
{
$amountSum = MoneyTradeDeposit::sum('amount');
return view('home.stocks', compact('amountSum'));
}
public function support()
{
return view('home.support');
}
public function withdrawal()
{
$moneytrades = MoneyTrade::all();
$moneytradeDeposits = MoneyTradeDeposit::all();
$amountSum = MoneyTradeDeposit::sum('amount');
$withdrawal = Withdrawal::all();
$balance = Withdrawal::sum('amount');
return view('home.withdrawal', compact('moneytrades', 'moneytradeDeposits', 'amountSum',
'withdrawal', 'balance'));
}
}
web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('/send-mail', 'SendMailController#send')->middleware('auth');
Auth::routes();
Route::get('register/agreement', 'Auth\RegisterController#show')->name('register.agreement');
Route::get('/home', 'HomeController#index')->name('home')->middleware('auth');;
Route::get('/dashboard', 'HomeController#dashboard')->name('home.dashboard')->middleware('auth');
Route::get('/my-account', 'MyAccountController#index')->name('myaccount.index')->middleware('auth');
Route::patch('/my-account/update', 'MyAccountController#update')->name('myaccount.update')->middleware('auth');
Route::get('/stocks', 'HomeController#stocks')->name('home.stocks')->middleware('auth');
Route::get('/support', 'HomeController#support')->name('home.support')->middleware('auth');
Route::get('/withdrawal-information', 'HomeController#withdrawal')->name('home.withdrawal')->middleware('auth');
Route::resource('withdrawal', 'WithdrawalController')->middleware('auth');
Route::resource('moneytrade', 'MoneyTradeController')->middleware('auth');
Route::resource('moneytrade-deposit', 'MoneyTradeDepositController');
Route::get('/account-removed', 'MoneyTradeController#destroy')->name('mt.delete')->middleware('auth');
Route::get('/trading-account', 'MoneyTradeController#view')->name('mt.view')->middleware('auth');
Route::get('/trading-account/deposits', 'MoneyTradeController#deposit')->name('mt.deposit')->middleware('auth');
How can I achieve this and prevent other users to access other dashboards that's not their own? I don't have roles and just normal users. I just want to prevent one user from accessing other user's dashboard. Thank you!

Laravel Middleware Auth Group is not working

Good Day. I had a problem with my authentication which I always redirected back into the login page. I found out that when I add in routes/web.php with this code below
Route::group(['middleware' => 'auth'], function() {
}
the page is always redirected back to the login page. But when I remove that code above, I can proceed to the home page. I trying to wonder how to solve this. I use route group in my past projects and I don't have any problems with that.
UPDATE: I used php artisan test and remodify my ExampleTest.php codes.
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
use App\User;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function testBasicTest()
{
$this->assertTrue(true);
}
public function testApplication()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)
->withSession(['foo' => 'bar'])
->get('/');
}
}
These are the results
C:\xampp\htdocs\nuadu_helpdesk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:273
269| */
270| protected function getRawAttributes(array $attributes = [])
271| {
272| if (! isset($this->definitions[$this->class])) {
> 273| throw new InvalidArgumentException("Unable to locate factory for [{$this->class}].");
274| }
275|
276| $definition = call_user_func(
277| $this->definitions[$this->class],
1 C:\xampp\htdocs\nuadu_helpdesk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:296
Illuminate\Database\Eloquent\FactoryBuilder::getRawAttributes([])
2 C:\xampp\htdocs\nuadu_helpdesk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php:155
Illuminate\Database\Eloquent\FactoryBuilder::Illuminate\Database\Eloquent\{closure}()
inside routes.php file you not write where to redirect. so please add like below..
Route::group(['middleware' => 'auth'], function() {
return redirect('/'); //by default you can change it as your requirments.
}
I found out about my problem. I checked using the auth and dd. I used a different primary key with user_id and it is a string type. I forgot to declare it in my user.php
protected $primaryKey = 'user_id';
protected $keyType = 'string';
public $incrementing = false;
By default, the primary key will always be the id. If you declare a different column name that will serve as your primary key, don't forget to declare the codes that I stated above, or else you end not reading the auth or not logging in.

Use Auth in AppServiceProvider

I need the ID of the user who is logged in to get a photo in the profile table, here I am trying to use View but only in the index function that gets $profile, I want all files in the view to have $profile
public function index(){
$profil = Profil_user::where('user_id',$auth)->first();
View::share('profil', $profil);
return view('user.index');
}
I have also tried AppServiceProvider but I get an error in the form of a null value if I don't log in, is there a solution to my problem?
public function boot(){
$auth = Auth::user();
dd($auth);
}
exist several way to pass a variable to all views. I explain some ways.
1. use middleware for all routes that you need to pass variable to those:
create middleware (I named it RootMiddleware)
php artisan make:middleware RootMiddleware
go to app/Http/Middleware/RootMiddleware.php and do following example code:
public function handle($request, Closure $next) {
if(auth()->check()) {
$authUser = auth()->user();
$profil = Profil_user::where('user_id',$authUser->id)->first();
view()->share([
'profil', $profil
]);
}
return $next($request);
}
then must register this middleware in app/Http/Kernel.php and put this line 'root' => RootMiddleware::class, to protected $routeMiddleware array.
then use this middleware of routes or routes group, for example:
Route::group(['middleware' => 'root'], function (){
// your routes that need to $profil, of course it can be used for all routers(because in handle function in RootMiddleware you set if
});
or set for single root:
Route::get('/profile', 'ProfileController#profile')->name('profile')->middleware('RootMiddleware');
2. other way that you pass variable to all views with view composer
go to app/Http and create Composers folder and inside it create ProfileComposer.php, inside ProfileComposer.php like this:
<?php
namespace App\Http\View\Composers;
use Illuminate\View\View;
class ProfileComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$profil = Profil_user::where('user_id', auth()->id)->first();
$view->with([
'profil' => $profil
]);
}
}
now it's time create your service provider class, I named it ComposerServiceProvider
write this command in terminal : php artisan make:provider ComposerServiceProvider
after get Provider created successfully. message go to config/app.php and register your provider with put this \App\Providers\ComposerServiceProvider::class to providers array.
now go to app/Providers/ComposerServiceProvider.php and do like following:
namespace App\Providers;
use App\Http\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
View::composer(
'*' , ProfileComposer::class // is better in your case use write your views that want to send $profil variable to those
);
/* for certain some view */
//View::composer(
// ['profile', 'dashboard'] , ProfileComposer::class
//);
/* for single view */
//View::composer(
// 'app.user.profile' , ProfileComposer::class
//);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
}
}
3. is possible that without create a service provider share your variable in AppServiceProvider, go to app/Provider/AppServiceProvider.php and do as follows:
// Using class based composers...
View::composer(
'profile', 'App\Http\View\Composers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
I hope be useful
you can use this
view()->composer('*', function($view)
{
if (Auth::check()) {
$view->with('currentUser', Auth::user());
}else {
$view->with('currentUser', null);
}
});

Laravel Global Variable to specific views

I would like assistance with calling a global variable on Laravel app for specific pages or routes.
This is my current code which works on login
App\Providers\AppServiceProvider
public function boot()
{
view()->composer(['auth.login'], function ($view) {
$view->with('settings', AppSetting::where('id',1)->first());
});
}
This is the route for the login page
Route::get('/', function () {
return view('auth.login');
});
[Edit 1]
On the login page , I used this code bellow to get the app version
{{$settings->app_version}}
After digging a little I think a good solution might be caching your AppSetting Model.
Write the given code in App\Providers\RouteServiceProvider
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
parent::boot();
App::before(function($request) {
App::singleton('settings', function(){
return AppSetting::where('id',1)->first();
});
// If you use this line of code then it'll be available in any view
// as $settings but you may also use app('settings') as well
View::share('settings', app('settings'));
});
}
}
App::singleton will call once AppSetting::where('id',1)->first() and after one call your settings will be cached.
And you can use {{$settings->app_version}} in your view.
Reference: stackoverflow.com/a/25190686/7047493

Routing No hint path defined for [module-name]

I am using Laravel5.5 and Module package. I have one student module and want to make this as a default for front-end, so committed code of the laravel's default routes/web.php
Here is my student's routes:
<?php
Route::group(['middleware' => 'web', 'namespace' => 'Modules\Student\Http\Controllers'], function() {
/** Frontend routes which does not require authentication
*
*/
Route::get('/', 'FrontEndController#index')->name('frontend.home');
Route::get('/program-search', 'FrontEndController#programs')->name('student.programs');
Route::get('/univeristy-search', 'FrontEndController#univerities')->name('student.universities');
});
And here is my controller code:
<?php
namespace Modules\Student\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Modules\Admin\Http\Models\ProgramCategory;
use Modules\University\Http\Models\Program;
use Modules\Student\Http\Models\Student;
use Modules\University\Http\Models\University;
class FrontEndController extends Controller
{
/**
* Display a listing of the resource.
* #return Response
*/
public function index()
{
return view('student::index');
}
/**
* Show all programs
*/
public function programs(){
$categories = ProgramCategory::orderBy('catagory_name')
->where('status', '=', 'active');
$programs = Program::orderBy('program_name')
->where([
['status', '=', 'active']
]);
$programs->categories = $categories;
return view('student::program_list')
->withPrograms( $programs );
}
public function univerities()
{
return view('student::university_list');
}
}
only first route '/' is working. when I try to access '/program-search' and '/univeristy-search' it throws an error like "No hint path defined for [sutdent]. (View: /var/www/development/unigatenew/Modules/Student/Resources/views/university_list.blade.php)".
What is the wrong I am doing? can anybody help out this?
The mistake was including the same file name inside view. Renaming file name which was included solved the problem.

Resources