Laravel Controllers __construct Issue - php

So I am having a few dramas with my controllers. They seem to operate properly, however they don't seem to use __construct() at all in any of the controllers.. I'm trying to use this to update our users table to show last activity.
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use App\Helpers\UserHelper;
use App\Helpers\ForumHelper;
use App\Helpers\ShopHelper;
use Auth;
use Image;
use App\User;
use DB;
use Hash;
use File;
class AdminController extends BaseController
{
public function __construct() {
if ($_SERVER["HTTP_CF_CONNECTING_IP"]) {
$_SERVER["REMOTE_ADDR"] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
if(Auth::check()) {
$time = strtotime("now");
DB::table('users')->where('userid', Auth::user()->userid)->update(['lastactivity' => $time]);
}
}
Any idea what I can do to check and try and get it working again?
I'm running Laravel Framework 5.4.28
A project I did similar on was running Laravel Framework version 5.2.45 and worked fine when I was doing that so I'm confused why this is happening on a newer version.
Any ideas how I can otherwise go about implementing the DB Update when loading stuff from my controllers?

If you want an activity tracker then add a web route middleware:
class ActivityTrackerMiddleware {
public function handle($request,$next) {
if ($request->user()) {
$request->user()->lastactivity = Carbon::now();
$request->user()->save();
}
return $next($request);
}
}
Add this in your web middleware:
'web' => [ ...
StartSession::class,
ActivityTrackerMiddleware::class,
...
];
You can also limit it to the admin controller if you prefer.

Related

why i have this wierd problem about my route

i'm working on a livewire project based on laravel ... every think was normal till yesterday my project didn't find some route and i recieved 404 .
for example one of my routes is /category/index
use App\Http\Livewire\Admin\Home as AdminPanel;
use App\Http\Livewire\AdminAuth\Register as AdminRegister;
use App\Http\Livewire\AdminAuth\Login as AdminLogin;
use App\Http\Livewire\AdminAuth\ForgotPassword as AdminForgotPassword;
use App\Http\Livewire\Category\Create as AddCategory;
use App\Http\Livewire\Category\Categories as Cats;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/home',AdminPanel::class)->middleware('auth')->name('Home');
Route::get('/admin/register',AdminRegister::class)->name('Admin.Register');
Route::get('/admin/login',AdminLogin::class)->name('Admin.Login');
Route::get('/admin/forgot-password',AdminForgotPassword::class)->name('Admin.ForgotPassword');
Route::get('/category/create',AddCategory::class)->name('create.category');
Route::get('/category/index',IndexCategory::class)->name('index.category');
my controller :
namespace App\Http\Livewire\Category;
use App\Models\Category;
use Livewire\Component;
use Livewire\WithPagination;
class Index extends Component
{
use WithPagination;
public $cat_id;
protected $listeners=['cat_id'=>'CatID'];
public function CatID($id){
$this->cat_id=$id;
}
public function render()
{
$cat=Category::findOrFail($this->cat_id);
$categories=Category::with('childrenRecursive')->where('parent_id',null)->paginate(15);
return view('livewire.category.index',compact('categories','cat'))->extends('layouts.admin')->section('content');
}
}
i tried all optimization artisan code like clear cache and clear route but it didn't work

Method App\Http\Controllers\FrontendCourseController::update does not exist

I have created the web route correctly.
use App\Http\Controllers\FrontendCourseController;
Route::get('update-item', [FrontendCourseController::class, 'update'])->name('update-item');
and add a method update. Also, I have created controller correctly.
<?php
namespace App\Http\Controllers;
use App\Helpers\CurrencyHelper;
use Auth;
use DB;
use App\Models\Course\Course;
use App\Models\Item;
class FrontendCourseController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function update()
{
dd('Page Update is working');
return view('update-item');
}
}
But I keep getting this error message
Method App\Http\Controllers\FrontendCourseController::update does not
exist.
Despite clearing caches using
php artisan route:cache
Where am I doing wrong?

Deleting models from database after Laravel Dusk tests have run?

I'm just starting out with looking at Dusk - and I'm testing some user functionality.
Below is my current test, however I'm trying to clean up after myself - for example the newly created user should be deleted from the database once it's done.
I've tried to use a tearDown method, but it doesn't seem to be be actually deleting it.
How would I typically go about spinning up temp models which need to be garbaged after?
<?php
namespace Tests\Browser;
use App\User;
use Tests\DuskTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class LoginTest extends DuskTestCase
{
protected $user = null;
public function testIfPublicUsersLogin()
{
$this->user = $user = factory(User::class)->create([
'is_student' => 0
]);
$this->browse(function ($browser) use ($user) {
$browser->visit('/login')
->assertVisible('#email')
->type('#email', $user->email)
->type('#password', 'secret')
->press('#loginButton')
->assertPathIs('/play');
});
}
public function tearDown()
{
if ($this->user) {
User::destroy($this->user->id);
//$this->user->delete();
}
}
}
There are multiple ways to achieve this:
Use the DatabaseTransactions trait so that there's a transaction rollback after every test. To do so add: use Illuminate\Foundation\Testing\DatabaseTransactions; in your php file and add use DatabaseTransactions; in your test class
You might want to use the DatabaseMigrations trait if you want to migrate and migrate rollback before and after every test rather than wrap them into transactions. To do so add: use Illuminate\Foundation\Testing\DatabaseMigrations; in your php file and add use DatabaseMigrations; in your test class
If you want to use custom setup and teardown methods, use the
afterApplicationCreated and beforeApplicationDestroyed methods
instead to register callbacks
<?php
namespace Tests\Browser;
use App\User;
use Tests\DuskTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class LoginTest extends DuskTestCase
{
protected $user = null;
public function testIfPublicUsersLogin()
{
$this->user = $user = factory(User::class)->create([
'is_student' => 0
]);
$this->browse(function ($browser) use ($user) {
$browser->visit('/login')
->assertVisible('#email')
->type('#email', $user->email)
->type('#password', 'secret')
->press('#loginButton')
->assertPathIs('/play');
$user->delete();
});
}
}
this code line $user->deletedelete your data after test. The tearDown method is useless.

Laravel session value is not showing in app/Hlepers/common_helpers.php and the base controller

I am a beginner in laravel and developing an application in Laravel 5.3. I created one common_helper.php file in app/Helpers directory and created a service provider and added it in config/app.php.
I tried to call a function located in the common helper from my controller. It is going to the helper file. But Not showing the session value in the common helper, which is available in the controller.
I already did something in laravel 5.2. But there the same structure working perfectly
What may be the issue? I couldn't figure out it. Please help
common_helper.php
<?php
use App\User;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Route;
use App\Http\Requests;
use App\Menu_master;
use Illuminate\Support\Facades\Input;
use Intervention\Image\Facades\Image as Image;
function check_session()
{
echo Session::get('email');die;
if (Session::has('email') && Session::has('login') && Session::has('role_id') && Session::has('role_name'))
{
if (empty(Session::get('email')) || Session::get('login') !== 'true' || empty(Session::get('role_id')) || empty(Session::get('role_name')))
{
Session::flush();
Redirect::to('/')->send();
exit(0);
}
}
else
{
Session::flush();
Redirect::to('/')->send();
exit(0);
}
}
I am calling the check_session() from the controller construct function like below
public function __construct(){
check_session();
}
You should use the session's namespace first.
use Session;
//or
use Illuminate\Support\Facades\Session;

Laravel 5 Auth Redirecting - It works, but is it correct?

Let me try to explain this.
If a guest goes to the / directory, he is welcome. If the guest tries to go to the /start directory, he is redirected to the log in page.
After a guest logs in, he is redirected to the /start directory. If a logged in user goes to the / directory, he is again redirected to the /start directory. (no need to see home page once logged in).
I got it working how I want, however I'm not sure if I'm doing this how Laravel intends for it to be done being that there is some non-DRY code in my PagesController.php. Plus, I'm basically redirecting the PagesController to the PagesController (doesn't sound like that follows good practices to me).
Here is the routes.php:
<?php
Route::get('', 'PagesController#index');
Route::get('start', 'PagesController#start');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
Here is the PagesController.php:
<?php
namespace App\Http\Controllers;
use App\HowItWorksModel;
use App\WhatYouGetModel;
use App\StartContentModel;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class PagesController extends Controller
{
public function index()
{
if (Auth::check()) {
return redirect()->action('PagesController#start');
}
$howItWorksContent = HowItWorksModel::all();
$whatYouGetContent = WhatYouGetModel::all();
return view('pages.index', compact(
'howItWorksContent',
'whatYouGetContent'
));
}
public function start()
{
if (Auth::check()) {
$startContent = StartContentModel::all();
return view('pages.start', compact(
'startContent'
));
}
return redirect('/auth/login');
}
}
How can I restructure this to work exactly as it works now but having better practices in mind? Or is what I'm doing perfectly okay for these purposes?
It is better done with middlewares, using middlewares will take the authentication resposability of your controllers and let it worry about content, this will make your controllers light and maintainable.
You should use Auth Middleware
You could try something like this. Not much different than what you had but does result in less code.
<?php
namespace App\Http\Controllers;
use App\HowItWorksModel;
use App\WhatYouGetModel;
use App\StartContentModel;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class PagesController extends Controller
{
public function __construct()
{
$this->middleware('auth', ['except' => 'index']);
}
public function index()
{
if (Auth::check())
return redirect('start');
$howItWorksContent = HowItWorksModel::all();
$whatYouGetContent = WhatYouGetModel::all();
return view('pages.index', compact(
'howItWorksContent',
'whatYouGetContent'
));
}
public function start()
{
$startContent = StartContentModel::all();
return view('pages.start', compact(
'startContent'
}
}

Categories