Passing Data in Login and Register Page Laravel 6 - laravel

I create login and register function in Laravel 6 with scaffold function, and i got this LoginController:
<?php
...
...
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
I want to pass a data DB::table('terms_condition')->get() to login view, how should i do?

Put this method in LoginController
public function showLoginForm()
{
$terms_condition = DB::table('terms_condition')->get();
return view('auth.login',compact('terms_condition'));
}
showLoginForm() is from AuthenticatesUsers trait which is used by your LoginController. You have to put this method in LoginController.

Inside your login controller rewrite the function showLoginform
public function showLoginForm()
{
` $data = DB::table('terms_condition')->get();
return view('frontend.auth.login',compact('data'));
}
Or From your LoginController you can see that AuthenticateUsers
go to the Authenticate Users file and edit the showLoginForm as like this
public function showLoginForm()
{
` $data = DB::table('terms_condition')->get();
return view('frontend.auth.login',compact('data'));
}
And dont forget to use DB in the top

You can override the built-in showLoginForm() method in the LoginController
LoginController.php
use Illuminate\Support\Facades\DB;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('admin.login',['terms'=>DB::table('terms_condition')->get()]); //pass your data here as a second argument
}
}
You can then access this in your blade view as $terms

A different way to go about it: use a View Composer. This will run when the view is rendered so you can pass data to it this way:
view()->composer('auth.login', function ($view) {
$view->with('something', DB::table(...)->get());
});
// or View::composer(...) if you prefer
You can add that at a Service Provider's boot method. No overriding anything.
Laravel 6.x Docs - Views - View Composers View::composer()

Related

How to use policy in laravel livewire (return, it is not a trait)?

I have category policy as below partial code.
class CategoryPolicy
{
use HandlesAuthorization;
public function view(User $user, Category $category)
{
return true;
}
}
Then, I call from livewire component inside the mount method.
class Productcategorysetup extends Component
{
use CategoryPolicy;
public function mount()
{
$this->authorize('view',CategoryPolicy::class);
}
}
I got an error message
App\Http\Livewire\Generalsetting\Productcategorysetup cannot use App\Policies\CategoryPolicy - it is not a trait
Any advice or guidance on this would be greatly appreciated, Thanks.
To use authorization in Livewire, you need to import the AuthorizesRequests trait first, and use that in your class.
Secondly, the first argument to authorize() when using view, is the instance of a model - in your case, a category. But this sounds like you want to list categories, i.e. the "index" file - which means you want to check for viewAny (as view is for a specific resource). In that case, the second argument is the class-name of the model, rather than the instance of a model.
<?php
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Models\Category;
class Productcategorysetup extends Component
{
use AuthorizesRequests;
public function mount()
{
$this->authorize('viewAny', Category::class);
}
}
Then in your policy,
class CategoryPolicy
{
use HandlesAuthorization;
public function viewAny(User $user)
{
return true;
}
public function view(User $user, Category $category)
{
return true;
}
}

Laravel route model binding without global scope

I have following route group in my laravel 8.0 app:
Route::prefix('offline_transaction')->name('offline_transaction.')->group(function () {
Route::post('/approve/{transaction:uuid}', [OfflineTransactionController::class, 'approve'])
->name('approve');
Route::post('/reject/{transaction:uuid}', [OfflineTransactionController::class, 'reject'])
->name('reject');
});
And Transaction model is:
class Transaction extends Model implements CreditBlocker
{
//....
protected static function boot()
{
parent::boot();
static::addGlobalScope(new AuthUserScope());
}
//....
}
And this is my AuthUserScope:
class AuthUserScope implements Scope
{
private string $fieldName;
public function __construct($fieldName = 'user_id')
{
$this->fieldName = $fieldName;
}
public function apply(Builder $builder, Model $model)
{
$user = Auth::user();
if ($user) {
$builder->where($this->fieldName, $user->id);
}
}
}
Now the problem is when an admin wants to approve or reject a transaction, 404 Not found error will throws. How can I pass this?
Customizing The Resolution Logic
If you wish to define your own model binding resolution logic, you may
use the Route::bind method. The closure you pass to the bind
method will receive the value of the URI segment and should return the
instance of the class that should be injected into the route. Again,
this customization should take place in the boot method of your
application's RouteServiceProvider:
Solution
What you can do is change the parameter name(s) in your routes/web.php file for the specific route(s).
Route::prefix('offline_transaction')->name('offline_transaction.')->group(function () {
Route::post('/approve/{any_transaction}', [OfflineTransactionController::class, 'approve'])
->name('approve');
Route::post('/reject/{any_transaction}', [OfflineTransactionController::class, 'reject'])
->name('reject');
Note the any_transaction. Change that to whatever naming convention you find most convenient.
Then, in your app/Providers/RouteServiceProvider.php file, change your boot(...) method to something like this:
use App\Models\Transaction;
use Illuminate\Support\Facades\Route;
// ...
public function boot()
{
// ...
Route::bind('any_transaction', function($uuid) {
return Transaction::withoutGlobalScopes()->where('uuid', $uuid)->firstOrFail();
});
// ...
}
// ...
Then in your controller app/Http/Controllers/OfflineTransactionController.php file, access the injected model:
use App\Models\Transaction;
// ...
public function approve(Transaction $any_transaction) {
// ...
}
// ...
Credits: Using Route Model Binding without Global Scope #thomaskim
Addendum
If you would like to remove a specific global scope from the route model bound query, you may use
withoutGlobalScope(AuthUserScope::class) in the boot(...) method of the app/Providers/RouteServiceProvider.php file.
Another approach is that I can use Route::currentRouteNamed in AuthUserScope class as following, which I prefer to use instead of Route::bind:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
class AuthUserScope implements Scope
{
private string $fieldName;
public function __construct($fieldName = 'user_id')
{
$this->fieldName = $fieldName;
}
public function apply(Builder $builder, Model $model)
{
$user = Auth::user();
if ($user && !Route::currentRouteNamed('admin.*')) {
$builder->where($this->fieldName, $user->id);
}
}
}

Laravel Resource Routing not showing anything when directly call method

I am stuck in resource routing
when I enter url netbilling.test/customer it goes to customer index file but when I enter url netbilling.test/customer/index nothing is returned. Also guide me if I have to route different method than in resource what is the method for that.
here is my web.php,
Route::get('/dashboard', function () {
return view('dashboard/index');
});
Route::resource('/customer','CustomerController');
here is my customer controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Customer;
use App\Package;
use Redirect,Response;
class CustomerController extends Controller
{
public function index()
{
$packages = Package::get();
$customers = Customer::orderBy('id', 'DESC')->get();
return view('customer/index', compact('customers','packages'));
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show($id)
{
//
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
}
}
Without custom route specification, this is how the index route maps to a Resource Controller, taken from Actions Handled By Resource Controller:
Verb
URI
Action
Route Name
GET
/photos
index
photos.index
So if you want URI /customer/index to work, then you need to specify this explicitly in your Controller:
use App\Http\Controllers\CustomerController;
Route::resource('customer', CustomerController::class);
Route::get('customer/index', [CustomerController::class, 'index'])->name(customer.index);

Laravel 5.6 - Get Route By Name In Controller

Within my login controller there is a hardcoded URL string which sets where to redirect to once the user has logged in. I am trying to make this dynamic by getting the route by name:
protected $redirectTo = '/home';
Updated To:
protected $redirectTo = route('home');
However the above give the following error:
FatalErrorException (E_UNKNOWN)
Constant expression contains invalid operations
Is it possible to get the URL to the route by its name?
You can use
request()->route()->getName()
To get the url you would use
request()->url()
And the path
request()->path()
Current route method
request->route()->getActionMethod()
In the case of redirectTo you can override the function:
protected function redirectTo() {
return route('foo.bar');
}
Your problem is that you're not allowed to use a function call when declaring a property in your class. You should use your controller's constructor to set it:
class LoginController extends Controller
{
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->redirectTo = route('home');
}
}
Alternatively, you can define a redirectTo method which returns the location that you want the user to be redirected to after a successful login. You can then remove the $redirectTo property altogether:
class LoginController extends Controller
{
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function redirectTo()
{
return route('home');
}
}
You have to define a route named home
like this:
Route::get('/home', 'HomeController#index')->name('home');
or Route::get('/home', ['as' => 'home', 'uses' => 'HomeController#index']);
Another way to get route url
$route_url = \Request::route()->getURLByName("name of the route");
protected $redirectTo = route('home');
You cannot assign a function to property. That's why you are getting this error.
you can do this in your constructor like
public function __construct(){
$this->redirectTo = route('home')
}
This is the way which i use and it will work with you.just put this function in your LoginController to override authenticated function.
protected function authenticated(Request $request, $user)
{
return redirect()->route('your_route_name');
}

Access a controller function on Auth::user();

I used the scaffolding tools to generate my authentication code for my laravel project. I created a UserController to make a profile page which works great but when I try to make a function that can be used on Auth::user() i get an error Call to undefined method Illuminate\Database\Query\Builder::admin()
Why isn't the admin function accessible on the Auth::user()? Doesn't that extend my UserController? Or am I mixing it up with the model? Is the the model a good place to check if my user is an admin?
Here is my user controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
class UserController extends Controller
{
/**
* Create a new user controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* #return View with user data
*/
public function index() {
$user = Auth::user();
return view('users.index', compact('user'));
}
/**
* #return bool
* Returns bool if the user is an admin.
*/
public function admin() {
$user = Auth::user();
$authorized_users = [
'admin#test.com'
];
return array_key_exists($user->email, $authorized_users);
}
}
and I am calling it on a different route controller function
public function index() {
return Auth::user()->admin();
}
I am fairly new to laravel and php so any critique is valuable and wanted!
You could add a function or attribute to you User model, I prefer attributes:
//User.php
class User extends Model{
protected $appends = ['is_admin'];
public function getIsAdminAttribute()
{
$user = Auth::user();
$authorized_users = [
'admin#test.com'
];
return array_key_exists($user->email, $authorized_users);
}
...
}
//Then in your view
Auth::user()->is_admin
No, Auth::user() does not extends any Controller. It represents the instance of the currently logged in/authenticated user. It will allow you retrieve other attributes of the use such as id, name etc Auth::user()->admin(); does not make any sense. Auth::user() has nothing to do with the UserController or any other controller.

Resources