Codeigniter access function in different controller - codeigniter

I am pretty new to codeigniter. I am facing an inconvenient issue. I have code like this in profile.php (controller):
public function edit()
{
$post = $this->input->post();
if($post)
{
//checking session username (if logged in)
if(isset($this->session->userdata('username') && !empty($this->session->userdata('username')))
{
}else{
/***************************REFERENCE DIFFERENT CONTROLLER HERE*********/
$this->load->view('login'); //should I write membership/index?
}
}else{
}
}
So I check if user logged in, if yes, code executes. if not, I wish to redirect to a function in different controller i.e. membership.php and it is the index() function of that controller. How can I reference that?

use redirect("membership/index"); for redirection in codeigniter

Use redirect variable
public function edit()
{
$post = $this->input->post();
if($post)
{
//checking session username (if logged in)
if(isset($this->session->userdata('username') && !empty($this->session->userdata('username')))
{
redirect('membership');
}else{
/***************************REFERENCE DIFFERENT CONTROLLER HERE*********/
$this->load->view('login'); //should I write membership/index?
redirect('membership'); // you can use this where u want to refrence/redirect
}
}else{
}
}

Related

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 - Use Middleware for restrict the user blocked profile?

I am working on a project in Laravel, it's a scratch of a social network. I have a important question. I have a controller with the profile of the user, there first of all i look if the user exists, if not exists it gets a 404, if exists get the data and the controller sends it to the view.
But now I was thinking that I can do a Blocking System between users. I created the table with N:n, were it's the user id who blocked and the user id of the destiny.
I made a Middleware to check if the users is blocked. But this middleware is executed on the route, and this means is executed before check if the user exists. It doesnt make me any problem. It's all working but my question is: This the best solution? It's better use a policy?
User Model
public function usersBlockedI()
{
return $this->belongsToMany(User::class, 'u_blocks', 'u_from', 'u_to');
}
u_blocks is the name of the table.
u_from is the name of the user who made the block.
u_to the user who received the block.
User Controller:
public function showProfile($username)
{
$profileUser = User::where('username', $username)->first();
if ($profileUser == null) {
return abort(404);
} else {
$profileUser['dataUser'] = dataUser::where('u_id', $profileUser['id'])->first();
return view('user.profile', compact('profileUser'));
}
}
Block Middleware
public function handle($request, Closure $next)
{
if (auth()->user()) {
$usernameProfile = $request->route('username');;
$ActualuserID = auth()->user()->id;
$checkIfBlocked = User::where('username', $usernameProfile)->first()->usersBlockedI->where('id', $ActualuserID);
if (!sizeof($checkIfBlocked) == 0) {
abort(404);
}
}
return $next($request);
}
Routes
Route::group(['middleware' => 'blocked'], function () {
Route::get('/{username}', 'UserController#showProfile')->name('showProfile');
});

Laravel LoginController condition don't work everytime

I want to block the login access to some users who are in blocked structures , it's working the first time but when i go back to the navigator and i try again to login the user can access to the application. i don't know why .. any idea ?
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function authenticated(Request $request, $user)
{
$blacklist = Structure::where('blocked' , '=' , 1)->pluck('id')->toArray();
$structure_id = $user->structure->id;
if(in_array($structure_id,$blacklist)){
return redirect('compte-bloque');
}else{
return redirect('/home');
}
}
The authenticated method is called after the user has been logged in to the site so you will need to log them out again.
Also, you can probably simplify you're logic quite a bit here. Assuming that Structure is the same model as $user->structure you should be able to do:
protected function authenticated(Request $request, $user)
{
if ($user->structure->blocked) {
auth()->logout();
return redirect('compte-bloque');
}
}

Is it better to query a database from the controller or with a model function in laravel?

Currently I am using the following code in my controller to query the database. This code checks whether a user has set their username yet.
$user = User::where('email', $userdata['email'])->first();
if(empty($user->username)){
echo 'Set username here...';
} else {
echo 'My home page!';
}
My question is, is it better to make a function in the User model to do this, or keep it as it is. So for example, the first line would be removed and in the if statement it would call the model function which would give true or false.
My initial thought is this should be moved to a model function as MVC structured projects should have 'fat models' and 'skinny controllers'. This is 'business logic' so should be in the model. If so, could you give an example on how I would move this to a model and call the function from the controller.
You should definitely move all data related code to the model. You've asked for an example. I'd create this method in a model:
public function findByEmail($email)
{
return $this->where('email', $email)->first();
}
In the controller:
use App\User;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function showSomething($userdata)
{
return view('some.view', [
'user' => $this->user->findByEmail($userdata['email'])
]);
}
In a view:
{{ empty($user->username) ? 'Hello anonymous' : $user->username }}
In this example, it looks like moving query in the model is not very good idea, but when your application will grow you'll see this is the only good way to work with data. It's MVC. Also, you should keep validation logic in the Request classes, business logic in their own classes etc.
You could write in your User.php model a function like :
public function hasUsername()
{
if($this->username)
{
return true;
}
return false;
}
and in your controller you could say:
$user = User::where('email', $userdata['email'])->first();
if($user->hasUsername())
{
// do somethin
}
Model
public static function checkIfUsernameExists($email) {
$user = User::where('email', $email)->first();
if (empty($user->username)) {
return true;
} else {
return false;
}
}
Controller
if(User::checkIfUsernameExists($userdata['email'])){
echo 'Set username heree...';
} else {
echo 'My home page!';
}

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