Shared data between certain views in Laravel - php

I want to share data on all my frontend views but not on the backend or dashboard pages.
view()->composer('*', function ($view)
{
// Some eloquent queries to return data that would only be used on frontend pages/views
view()->share('data', $data);
}
The problem with this approach is that it runs on every view render, is there a way i can limit it to only frontend views?
As an alternative i am thinking to create separate routes group and with some middleware to share the data between route group something like below
Route::group(['middleware' => ['frontend']], function () { //Frontend Routes });
// frontend Middleware
public function handle(Request $request, Closure $next)
{
View::share(
'data', 'data'
);
return $next($request);
}
Can someone please guide me what is the best approach to handle this?

Related

Laravel share variable to views in custom middleware group

I need to put $page variable into views in some group of routes. I found one solution to put routes in middleware group and in middleware use View::share. But if I place any function in middleware will this code run for
How does view composer work? Does it try to run function on each view? I'm just thinking about performance if one page is from multiple views....
Middleware:
public function handle(Request $request, Closure $next)
{
View::share('page', Page::get());
return $next($request);
}
Will query for getting Pages get called once for multiple views?

Using multiple authentication middlewares for one route

I have a requirement where there is an API method (guarded by the well-known package tymon/jwt-auth) and I need to also be able to access it using the basic session based web middleware.
I don't want to repeat the route in both api.php and web.php even though that would totally work.
I tried adding both to the route but they simply don't work, like: ['auth:api', 'web']
I also tried creating a new middleware with the intention of checking both api and web like so:
class CombinedAuth
{
public function handle($request, Closure $next)
{
$web = Auth::guard('web')->user();
if ($web) {
return $next($request);
}
$api = Auth::guard('api')->user();
if ($api) {
return $next($request);
}
if(!$web && !$api) {
throw new AuthorizationException;
}
}
}
and that also doesn't work. The api middleware works fine but the web middleware doesn't and it always signs me out and redirects to the login page.
So Is there a neat way of protecting a route with api and web middlewares at the same time in Laravel 5.8?
You can use 'auth:api,web' to check for multiple guards.
Using multiple can middleware calls in Laravel 9 route;
<?php
Route::get('/', function () {
return view('money');
})
->middleware([
'can:manage,App\Models\Payment',
'can:manage,App\Models\Withdraw',
]);
?>

Check the user's auth in all controllers' actions

I use Laravel 5.3 and I have the following problem.
[UPDATE]
My initial trouble was the appearance of an error when performing actions on the site when the user was not logged in the system.
This happened when the browser is started, where cached information is displayed by default on the page. Site interface displayed for logged users, and in his system was not. At the same time, producing some action, I get an error that the user is not authorized.
I also have group auth middleware for all my routes. When I reboot page of the site, the middleware is activated and redirectedme to the login page. The main problem is the browser shows the cached information.
So, in addition to middleware for routes I decided to make auth check in controllers.
[/UPDATE]
I want to check user's auth in every controller's action. Making the auth check in every controllers' action manually isn't a solution, because there are many controllers and actions.
So I decided to make it globally.
As all controllers extends Main Controller (App\Http\Controllers\Controller.php), I decided write the
auth()->check() in constructor:
function __construct()
{
if(auth()->check()) dd('success');
}
But... nothing happened((( Then I found the callAction method in BaseController which Main Controller extends and made checking here:
public function callAction($method, $parameters)
{
if(auth()->check()) dd('success');
return call_user_func_array([$this, $method], $parameters);
}
This time everything's OK, but I don't like this solution, because editing the core files isn't good.
Finally, I redeclared callAction method in Main Controller with auth checking, but I don't like this way too.
Is any solution?
You should use middleware:
Route::get('profile', ['middleware' => 'auth', 'uses' => 'UserController#showProfile']);
Or:
Route::get('profile', 'UserController#show')->middleware('auth');
Or using middleware groups:
Route::group(['middleware' => ['auth']], function () {
// Controllers here.
});
Or using controller's construct:
public function __construct()
{
$this->middleware('auth');
}
You can use auth middleware in your controller
public function __construct()
{
$this->middleware('auth');
}
check here : https://laravel.com/docs/5.3/authentication
if there is a group of routes this would be the easiest way
Route::group(['middleware' => ['auth']], function()
{
// here all of the routes that requires auth to be checked like this
Route::resource('user','UsersController');
}
another ways
function __construct()
{
$this->middleware('auth');
}
another way is specified on controller routes
Route::get('profile', [
'middleware' => 'auth',
'uses' => 'UserController#showProfile'
]);
see documentation
https://laravel.com/docs/5.0/controllers#controller-middleware

Laravel Redirection doesn't work

I am using Laravel 5.1. My controller is specifically for admin users. So I check whether user is admin or not.This is my code.
public function getAdminData()
{
$this->checkAdminStatus();
return response()->json(array('admin-data'));
}
public function checkAdminStatus()
{
$userManager = new UserManager();
if(!$userManager->isAdmin())
{
return redirect()->route('returnForbiddenAccess');
}
}
My route is
Route::any('api/app/forbidden',['uses' =>'ErrorController#returnNonAdminErrorStatus','as'=>'returnForbiddenAccess']);
Now if user is not admin, then it should not return admin-data yet it returns. Shouldn't it stop processing logic after redirect()->route call?
Also this is purely REST application.
Why don't you use Laravel Middleware solution for your need ? You can link a middleware to your controller, checking if the current user is an administrator, and redirect if not :
//You Middleware Handle method
public function handle($request, Closure $next)
{
if ($this->auth->guest() || !($this->auth->user()->isAdmin))
{
return redirect('your/url')->with('error','no admin');;
}
return $next($request);
}
You can add on or multiple middleware for a controller in his construct method
//your controller
public function __construct(Guard $auth, Request $request){
$this->middleware('auth', ['except' => ['index', 'show']]); //here one 'auth' middleware
$this->middleware('admin', ['only' => ['index', 'show', 'create','store']]); //here the admin middleware
}
Notice the onlyand except parameters that allow or disallow the middleware for some controller methods
Check laravel documentation on Middleware for more information :)
No, your logic is slightly flawed. The return value you are sending back from checkAdminStatus() is simply being ignored and thrown away:
public function getAdminData()
{
// You don't have $redirectValue in your code, but imagine it
// is there. To actually redirect, you need to return this value
// from your controller method
$redirectValue = $this->checkAdminStatus();
Nothing is being done with that redirect. The only time something is being returned from your controller is happening on every single request. I would suggest something more like this:
public function getAdminData(UserManager $userManager)
{
if($userManager->isAdmin()) {
return response()->json(array('admin-data'));
}
return redirect()->route('forbidden-access');
}
I think this captures the spirit of your question: the only time anything is being returned here is if the user is an admin.
As an aside, you are returning JSON data in one case, and a redirect in another. This may not be a very good idea. My reasoning is because, normally, JSON data is returned in response to AJAX requests, which in my experience are seldom followed up with an actual redirect in the event of failure. (YMMV)

How to ensure user is authenticated before he publishes an article in Laravel in the below scenario?

I am developing a simple web blogging application in Laravel 5.1. The application contains two controllers, a UsersController and an ArticlesController.
The authenticate() and check() functions that validate whether the user is authorized to carry out the operation are in the UsersController, and the store(), update() etc. features related to articles are in the ArticlesController.
How am I supposed to call the authenticate() or check() function from ArticlesController before say, store()ing an article to the database?
Laravel uses middleware, in your controller you need to put this
public function __construct(){
$this->middleware('auth'); //Requires auth
}
and in your routes you need to add the code for use middleware in your needed controllers like this
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
Read the documentation of Laravel about Middleware you can create more middleware http://laravel.com/docs/master/middleware
You're question is not very clear, but I suppose that you want check if an user is authenticated before storing an article. There are many ways to do it:
Set a middleware in the routing rules of your ArticleController.
Check the authentication in the store method using the "standard" Auth class.
Example:
function store()
{
if (Auth::check())
{
// The user is logged in...
}
}

Categories