How to set the global variable on Laravel Controller? - laravel

Everyone.
Every function on a controller, I am using the same variables.
public function store(Request $request)
{
$user = auth()->user();
$user_name = $user->name;
$user_id = $user->id;
$init_pdf = url('/') . '/images/' . 'upload/' . $user_name . '/' . $name;
...
}
public function signedPdf(request $request)
{
$user = auth()->user();
$user_name = $user->name;
$user_id = $user->id;
$name = $user_name . $user_id . '.' . $file->extension();
...
}
I want to set the global variable for the common variables.
How can I set it?
thanks

Normally you can directly set things in the constructor but there is an issue with Controllers in regards to middleware. The Controller is resolved before the request has passed through the middleware stack. Which means you usually won't have things like sessions or auth available yet. You would want to use a closure based middleware in the constructor of the Controller to be able to set this value:
protected $user;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = $request->user();
// also can set other variables here as well
// let the request continue through the stack
return $next($request);
});
}
Then you should have access to $this->user in your methods.
Another answer: Assign user values for whole controller in laravel
Duplicate of that basically.

This solution is worked for me
In
app/Http/Controllers/Controller.php
Import Illuminate\Support\Facades\Auth
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth; <--- like this
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected $userId;
protected $userName;
public function __construct()
{
$this->userId = Auth::user()->id;
$this->userName = Auth::user()->name; <--- "Admin"
}
}
Now $this->userId and $this->userName is available wherever extends Controller
For example:
app/Http/Controllers/API/v1/ConfigController.php
class ConfigController extends Controller
{
public function index() {
return $this->userName; <--- "Admin"
}

Related

Override default store function of a controller in Laravel 7

I am working on a Laravel application that has some modules implemented.
Now, the one of the modules extends a default controller and should be able to override the default store() function
I tried the following:
namespace App\Http\Controllers\Admin;
class OriginalController extends AdminBaseController
{
public function store(Request $request)
{
$model = new Model();
$model->name = $request->name;
$model->save();
}
}
In the module:
namespace Modules\CustomModule\Http\Controllers\Admin;
class ExtendedController extends OriginalController
{
public function store(Request $request)
{
$model = new Model();
$model->name = $request->name;
$model->newInfo = $request->newInfo;
$model->save();
}
}
Even if I set the web.php routes for the new controller, the store() function will only look at the original one
Could someone tell me what am I missing?
Thank you!

Automatically logout after refreshing the page in laravel 6

I am Automatically logout after refreshing the page in laravel 6. Everything is working fine but I am successfully logged in but when I refresh the page automatically logged out. I am using a socialite package to login to my app. I also increase the session lifetime to 180 in config/session.php file but still didn't work...
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use App\Models\Constant_model;
use App\SocialProvider;
use App\User;
use Socialite;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
// public function __construct()
// {
// $this->middleware('guest')->except('logout');
// }
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
$social_user = Socialite::driver($provider)->user();
$authuser = $this->findOrCreateUser($social_user,$provider);
Auth::login($authuser,true);
return redirect('/');
}
public function findOrCreateUser($social_user,$provider){
$authuser = SocialProvider::where('provider_id', $social_user->id)->first();
if(!$authuser){
$user = User::firstOrCreate(
['email'=> $social_user->getEmail()],
['ip_address'=> '127.0.0.1'],
['user_name'=> $social_user->getName()],
['name'=> $social_user->getName()],
['picture'=> $social_user->getAvatar()],
['password'=> 'sfdsfsdffsfsfs'],
);
$user->socialProviders()->create(
['provider_id'=>$social_user->getId(), 'provider'=>$provider]
);
return $user;
}else{
$user_id = $authuser->user_id;
$userdata = Constant_model::getDataOneColumn('users',"id",$user_id);
$user = User::firstOrCreate(
['email'=> $userdata[0]->email],
['ip_address'=> '127.0.0.1'],
['user_name'=> $userdata[0]->username],
['name'=> $userdata[0]->name],
['picture'=> $userdata[0]->picture],
['password'=> 'sfdsfsdffsfsfs'],
);
return $user;
}
}}

How to get current user id in constructor in laravel?

I am using laravel 5.7, but i can't get current user id in __construct().
I also tried Auth:id(), but it also not working.
How to get current user id in constructor?
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public $id;
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
return $next($request);
});
dd($this->id);
}
}
Current output is null.
You can only access the session in the closure. Just refactor your code to this:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
dd($this->id);
return $next($request);
});
}
You can now use the value $this->id in your controller methods.
In the example in your question, after you've set the value $this->id, you continue with the request. Since you try to access $this->id outside of the scope of the closure, it still is null in the datadump.
After return you will not go to next statement that's why it is not print.
If you want to use this in view then no need to pass in view you can simply access logged user id like this
{{Auth->user->id}}
if you wan to use this in controller make sure you are logged in.
Sometime session expired then you will not get user id
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public $id;
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
dd($this->id);
return $next($request);
});
}
}
The easiest solution is to create a middleware and call it later in the constructor.
php artisan make:middleware FoobarMiddleware
I recommend putting an alias in Kernel.php
protected $routeMiddleware = [
...
'foobar' => \App\Http\Middleware\FoobarMiddleware::class,
]
Constructor:
public function __construct()
{
$this->middleware('auth');
$this->middleware('foobar');
}
I recommend changing the focus of how you are creating everything

HttpException in Handler.php line 107: This action is unauthorized

I'm learning Laravel 5. I have finished the document's Quickstart - intermediate. I want to apply the authorize check for Task's actions to the User's. I want to check whether the target user is the current logged in user in order to use user's edit action. However, browser keeps telling me when I try to access http://myfirst.app/users/2/edit:
FatalThrowableError in UsersPolicy.php line 20:
Type error: Argument 1 passed to App\Policies\UsersPolicy::edit() must be an instance of Illuminate\Http\Request, instance of App\User given
Routes.php
Route::get('/users/{user}', 'UsersController#view');
Route::get('/users/{user}/edit', 'UsersController#edit');
Route::patch('/users/{user}', 'UsersController#update');
AuthServiceProvider.php
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
'App\Task' => 'App\Policies\TaskPolicy',
'App\User' => 'App\Policies\UsersPolicy',
];
UsersPolicy.php
namespace App\Policies;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Auth\Access\HandlesAuthorization;
class UsersPolicy
{
use HandlesAuthorization;
public function edit(Request $request, User $user)
{
return $request->user()->id === $user->id;
}
public function update(Request $request, User $user)
{
return $request->user()->id === $user->id;
}
}
UsersController.php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
protected $user;
public function __construct() {
$this->middleware('auth');
}
public function view(Request $request, User $user)
{
if($request->user()->id == $user->id){
return view('users.view', ['user' => $user]);
}
return redirect('/tasks');
}
public function edit(Request $request, User $user)
{
$this->authorize('edit', $user);
return view('users.edit', compact('user'));
}
public function update(Request $request, User $user)
{
$this->authorize('update', $user);
$user->update($request->all());
return redirect('/users/'.$user->id);
}
}
In the Document's TaskController's delete function, $user isn't passed into $this->authorized('destroy', $task) in order to allow TaskPolicy's destroy function to use $user:
TaskController.php
public function destroy(Task $task)
{
$this->authorize('destroy', $task);
$task->delete();
return redirect('/tasks');
}
TaskPolicy.php
public function destroy(User $user, Task $task)
{
return $user->id === $task->user_id;
}
Anyway, I followed the exception and added $request to UsersController's edit function's parameter
$this->authorize('edit', $request, $user);
And I get
HttpException in Handler.php line 107:
This action is unauthorized.
What should I do?
In your Request file set
public function authorize()
{
return true;
}
Try this: in UsersPolicy.php add:
enter code here/**
* #var User
*/
protected $user;
/**
* Create a new policy instance.
*
* #param User $user
*/
public function __construct(User $user)
{
$this->user = $user;
}
And in your UsersController.php change $this->authorize('edit', $user); to $this->authorize('edit');
Hope that helps
as per documentation: "The Gate will automatically return false for all abilities when there is not an authenticated user". So before doing any authorization, please check Auth::user() if it returns a currently authenticated user.

Laravel middleware redirection

when i use laravel middleware its routes is not work properly
<?php
namespace App\Http\Controllers;
use Auth;
use App\Article;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\ArticleRequest;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
//use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function __construct(){
$this->middleware('auth',['only'=>'create']);
}
//
public function index(){
//return \Auth::user();
$articles = Article::latest('published_at')->published()->get();
return view('articles.index',compact('articles'));
}
public function show($id){
$article = Article::findorFail($id);
//dd($article->published_at->addDays(8)->diffForHumans());
return view('articles.show',compact('article'));
}
public function create(){
if(Auth::guest()){
return redirect('articles');
}
return view('articles.create');
}
public function store(ArticleRequest $request){
/*
$input = Request::all();
$input['published_at'] = Carbon::now();
*/
$article = new Article($request->all());
Auth::user()->articles()->save($article);
//Article::create($request->all());
return redirect('articles');
}
public function edit($id){
$article = Article::findorFail($id);
return view('articles.edit', compact('article'));
}
public function update($id, ArticleRequest $request){
$article = Article::findorFail($id);
$article->update($request->all());
return redirect('articles');
}
}
when i go to http://localhost/lernlaravel/public/articles/create it works fine
but when i go to http://localhost/learnlaravel/public/articles it redirect to http://localhost/articles.
index() method is used for listing articles how i can fix it?
The redirect () accepts a URL path so if you want ensure your redirect will work on both testing and production environments, I would pass either action () or route () to all of your applications redirect calls. In your this case I would go with
return redirect(action ('ArticlesController#show', $articles->id));
This way Laravel will automatically generate the proper URL path to the controller you want to handle the request.
If you choose to go with route() you are required to have named the route in your routes file, but I find that with resourceful controllers it's less complicated to go with action.

Resources