How to print Last Executed Query on controller in Laravel 5.4? - laravel-5

I have created following method to verify admin in
AdminModel.php
public function verifyAdmin($where){
$admin = AdminModel::where($where)->get();
if($admin->isEmpty()){
$emptyArray=array();
return $emptyArray;
}else{
return $admin;
}
}
Now this model's method is used in controller as follows AdminController.php
public function adminLogin(AdminLoginRequest $request)
{
$adminModel = new AdminModel();
$email=$request->email;
$password=$request->password;
$where=array('email'=>$email,'password'=>md5($password));
$getUser=$adminModel->verifyAdmin($where);
if(!empty($getUser)){
session()->put('email',$email);
return redirect('admin-dashboard');
}else{
return redirect('admin')->with('error', 'Invalid email or password !');
}
}
Now I want to echo last executed query in the controller after the models method call .
How can I do this please suggest me, I am using Laravel 5.4

Related

Laravel authorization policy not working on Show page

I have a laravel app using Policies to assign roles and permissions, i cant seem to access the show page and im not sure what im doing wrong?
If i set return true it still shows a 403 error as well, so im unsure where im going wrong here. The index page is accessable but the show page is not?
UserPolicy
public function viewAny(User $user)
{
if ($user->isSuperAdmin() || $user->hasPermissionTo(44, 'web')) {
return true;
}
return false;
}
public function view(User $user, User $model)
{
if ($user->isSuperAdmin() || $user->hasPermissionTo(44, 'web')) {
return true;
}
return false;
}
UserController
public function __construct()
{
$this->authorizeResource(User::class, 'user');
}
public function index()
{
$page_title = 'Users';
$page_description = 'User Profiles';
$users = User::all();
return view('pages.users.users.index', compact('page_title', 'page_description', 'users'));
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show($id)
{
$user = User::findOrFail($id);
$user_roles = $user->getRoleNames()->toArray();
return view('pages.users.users.show', compact('user', 'user_roles'));
}
Base on Authorize Resource and Resource Controller documentation.
You should run php artisan make:policy UserPolicy --model=User. This allows the policy to navigate within the model.
When you use the authorizeResource() function you should implement your condition in the middleware like:
// For Index
Route::get('/users', [UserController::class, 'index'])->middleware('can:viewAny,user');
// For View
Route::get('/users/{user}', [UserController::class, 'view'])->middleware('can:view,user');
or you can also use one policy for both view and index on your controller.
I had an issue with authorizeResource function.
I stuck on failed auth policy error:
This action is unauthorized.
The problem was that I named controller resource/request param with different name than its model class name.
F. ex. my model class name is Acknowledge , but I named param as timelineAcknowledge
Laravel writes in its documentation that
The authorizeResource method accepts the model's class name as its first argument, and the name of the route / request parameter that will contain the model's ID as its second argument
So the second argument had to be request parameter name.
// Here request param name is timelineAcknowledge
public function show(Acknowledge $timelineAcknowledge)
{
return $timelineAcknowledge->toArray();
}
// So I used this naming here also
public function __construct()
{
$this->authorizeResource(Acknowledge::class, 'timelineAcknowledge');
}
Solution was to name request param to the same name as its model class name.
Fixed code example
// I changed param name to the same as its model name
public function show(Acknowledge $acknowledge)
{
return $acknowledge->toArray();
}
// Changed here also
public function __construct()
{
$this->authorizeResource(Acknowledge::class, 'acknowledge');
}
I looked over Laravel policy auth code and I saw that the code actually expects the name to be as the model class name, but I couldn't find it anywhere mentioned in Laravel docs.
Of course in most of the cases request param name is the same as model class name, but I had a different case.
Hope it might help for someone.

I can't use onlyTrashed method on datapanel in laravel

I have a problem with Laravel datatable SoftDelete method in Laravel. I use onlyTrashed() function to get the data but all data is coming.I am using the latest version yajrabox.
Frist try:
public function trash(Request $request){
$datalists = DataTables::of(Datapanel::onlyTrashed())->onlyTrashed()->make(true);
return view('back.cancelpanel');
}
Second try:
public function trash(Request $request){
if ($request->ajax()) {
return Datatables::of(Datapanel::onlyTrashed())
->onlyTrashed()
->make(true);
}
return view('back.cancelpanel');
}
Third try:(In this try i reached the data deleted with json data but I didn't know how to direct it to datatable.)
public function trash(Request $request){
$datalists = DataTables::of(Datapanel::onlyTrashed())->make(true);
return response()->json($datalists);
}

laravel 6 redirect back to page after login using socialite package [duplicate]

I have a page with a some content on it and a comments section. Comments can only be left by users who are signed in so I have added a login form to the page for users to sign in with (this only shows if they are not already logged in).
The problem I have is that when the user signs in they get redirected back to the home page and not the page they were previously on.
I have not changed the login method from the out of the box set-up.
Can anyone suggest a simple way to set the redirect url. My thoughts are that it would be good to be able to set it in the form.
Solution for laravel 5.3:
In loginController overwrite the showLoginForm() function as this one:
public function showLoginForm()
{
if(!session()->has('url.intended'))
{
session(['url.intended' => url()->previous()]);
}
return view('auth.login');
}
It will set the "url.intended" session variable, that is the one that laravel uses to look for the page which you want to be redirected after the login, with the previous url.
It also checks if the variable has been set, in order to avoid the variable to be set with the login url if the user submit the form with an error.
For Laravel 5.5, following code worked for me by just updating LoginController.php
public function showLoginForm()
{
session(['link' => url()->previous()]);
return view('auth.login');
}
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
Please use redirect()->intended() instead in Laravel 5.1
You can also see more about it here: http://laravel.com/docs/5.1/authentication
For Laravel 5.3
inside App/Http/Controllers/Auth/LoginController
add this line to the __construct() function
$this->redirectTo = url()->previous();
So the full code will be
public function __construct()
{
$this->redirectTo = url()->previous();
$this->middleware('guest', ['except' => 'logout']);
}
It works like a charm for me i'm using laravel 5.3.30
For Laravel 5.4, following code worked for me by just updating LoginController.php
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
Session::put('backUrl', URL::previous());
}
public function redirectTo()
{
return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
}
The Laravel 5.6, When user insert wrong credentials then login page will reload and session(['link' => url()->previous()]); will take login URL in link variable. So the user will redirect to a login page again or redirect to /home if login success. So to avoid these below code working for me! After that no matter how much time user insert wrong credentials he will redirect after login to exactly where he was before login page.
Update or overwrite public function showLoginForm() in LoginController.
public function showLoginForm()
{
if (session('link')) {
$myPath = session('link');
$loginPath = url('/login');
$previous = url()->previous();
if ($previous = $loginPath) {
session(['link' => $myPath]);
}
else{
session(['link' => $previous]);
}
}
else{
session(['link' => url()->previous()]);
}
return view('auth.login');
}
Also, Update or Overwrite protected function authenticated(Request $request, $user) in LoginController.
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
If you want to redirect always to /home except for those pages with comments, then you should overwrite your redirectTo method in your LoginController:
public function redirectTo()
{
return session('url.intended') ?? $this->redirectTo;
}
On all pages where you want to remain on the site, you should store the url for one request in the session:
public function show(Category $category, Project $project){
// ...
session()->flash('url.intended' , '/' . request()->path());
}
Redirect to login with the current's page url as a query string:
login
In your LoginController check if exists and save the query string in session then redirect to the url after login
public function __construct() {
parent::__construct();
if ( \request()->get( 'redirect_to' ) ) {
session()->put( 'redirect.url', \request()->get( 'redirect_to' ) );
}
$this->middleware( 'guest' )->except( 'logout' );
}
protected function authenticated(Request $request, $user) {
if(session()->has('redirect.url') {
return redirect( session()->get( 'redirect.url' ) );
}
}
Look into laravel cheat sheet
and use:
URL::previous();
to go to the previous page.
Laravel 5
(maybe 6 also, not tested, if someone knows it please update the answer)
add this to LoginController:
protected function redirectTo(){
return url()->previous();
}
Note: if present the field $redirectTo , remove it
in your RedirectIfAuthenticated.php change this code
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/contactus');
}
return $next($request);
}
please notice to :
return redirect()->intended('/contactus');
Inside your template file you can just use:
{{ url()->previous() }}
To redirect from the controller you should use
return redirect()->back();
or Just
return back();
use Illuminate\Support\Facades\Redirect;
public function Show_Login_Form()
{
$back = Session::put('url_back',url()->previous());
$current = url()->current();
if(Session::get('user_id'))
{
if ($back == $current) { // don't back Login Form
return Redirect::to('home');
}
elseif (Session::has('url_back')) {
return Redirect::to('home');
}
else{
return redirect()->back();
}
}
else{
if ($back == $current) {
return Redirect::to('home');
}
else{
Session::put('url_back',url()->previous());
}
return view('account.customer-account.login');
}
}
public function signin_user(Request $request) // Login post
{
$username = $request->input_username_login;
$password = md5($request->input_password_login);
$result = DB::table('tbl_user')
->where([['user_email',$username],['user_password',$password]])
->orWhere([['user_phone',$username],['user_password',$password]])
->first();
if($result){
Session::put('user_id', $result->user_id );
Session::put('user_name', $result->user_name);
Session::put('user_username', $result->user_username);
Session::put('user_avatar', $result->user_avatar);
return Redirect::to(Session::get('url_back')); // Back page after login
} else {
Session::put('message_box', 'Error !!!');
return redirect()->back();
}
}
You can use redirect back with Laravel 5:
<?php namespace App\Http\Controllers;
use Redirect;
class SomeController extends Controller {
public function some_method() {
return Redirect::back()
}
}
Use Thss
return Redirect::back('back-url')

Laravel Nova how to overwrite the nova LoginController

My project requires a username rather than email. I had this working in Laravel 5.8 and Nova v2.1.0. After upgrading to L 6.x N 2.6.1 everything broke. So I started over with clean L 6.x and N 2.6.1 install.
Now I want to customize the login but I do not want to edit any Nova Package scripts as before.
I've added this code to nova/Http/Controllers/LoginController.php and all works as expected.
public function username()
{
return 'username';
}
When I add the code to App/Nova/Http/Controller/LoginController.php (a copy of the original) the login still requires an email address. Or is using the original file in nova.
this is what i do on my end
i override the App\Http\Controllers\Auth\LoginController.php from
class LoginController extends Controller
to
class LoginController extends \Laravel\Nova\Http\Controllers\LoginController
if you want to use username or email on the login page you have to add this.
this method will determine how the user input they credential
public function username()
{
$login = \request()->input("email");
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
\request()->merge([$field => $login]);
return $field;
}
because the user can login using email or username but the default login from nova only have 1 input box. have to add this to display if the user input wrong username or that username did not exist
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
'email' => [trans('auth.failed')],
]);
}
on my controller i have add other method to determine if the user is admin or able to access the backend or if the user is still active.
protected function authenticated(Request $request, $user)
{
if($user->isSuperAdmin()) {
return redirect(config('nova.path'));
}
if($user->can('backend')) {
return redirect(config('nova.path'));
}
return redirect('/');
}
by adding method to check user is active i need to add this method to check if the user can login
private function activeUser($username)
{
$user = User::where($this->username(), $username)->first();
if($user) {
return $user->active;
}
return false;
}
public function login(Request $request)
{
$active = $this->activeUser($request->only($this->username()));
if(! $active) {
return $this->sendFailedLoginResponse($request);
}
return parent::login($request);
}
hope this helps

Laravel Auth::attempt() is not working?

I have added my code and problem..no one is available there to respond me .. please help me to solve this !
http://laravel.io/forum/10-25-2015-laravel-5120-lts-fails-to-authenticate
I dono what's wrong with laravel,
I have the following functions in same controller
public function signup()
{
$user=new User();
$user->email=Input::get('email');
$user->password=Hash::make(Input::get('Password'));
$user->username=$username;
$user->save();
// self authenticating user
Auth::attempt(['email'=>Input::get('email'),'password'=>Input::get('Password')],true);
return Auth::user();
}
the above Auth::attempt() is working fine but the next method to this signup is
public function login()
{
if( Auth::attempt(['email'=>Input::get('email'),'password'=>Input::get('password')],true))
{
return Auth::user();
}
else
{
echo "failed";
}
}
here the Auth is not working i dono y.. no errors with form
Did you make sure to give your inputs a name attribute? Laravels Input/Request Facades accesses them by the name, not id or class.
Have you tried the default AuthController ?

Resources