skip to Main Content

I’m trying to create a particular online address book where each user can register and create his contacts.

When the contacts are created, the "user_email" and "session_id" of the user who created it are saved in "students" tab.

This is the structure of the users table

This is the structure of the students table

This is the function "addStudent" present in "StudetsController" (Don’t pay attention to "ICF Dropdown")

<?php

namespace AppHttpControllers;

use AppStudent;
use AppProduct;
use Session;
use User;
use Auth;
use DB;
use IlluminateHttpRequest;
use function GuzzleHttpPromiseall;

class StudentsController extends Controller
{

public function addStudent(Request $request){
        if($request->isMethod('post')){
            $data = $request->all();
            $student = new Student();
            $student->student_sex = $data['student_sex'];
            $student->student_name = $data['student_name'];
            $student->student_surname = $data['student_surname'];
            $student->student_birth = $data['student_birth'];
            $student->codice_icf = $data['codice_icf'];
            if(!empty($data['description'])){
                $student->description = $data['description'];
            }else{
                $student->description = '';
            }
            $student->user_email = $data['user_email']=Auth::user()->email;
            if(empty($session_id)) {
                $student->session_id = $data['session_id']= str_random(40);
            }else{
                $student->session_id = Student::get('session_id');
            }
            $student->save();
            return redirect('/')->with('flash_message_success','Lo studente è stato creato con successo!');
        }

        //ICF drop down start
        $products = Product::get();
        $products_dropdown = "<option selected disabled>Codice ICF</option>";
        foreach($products as $pro){
            $products_dropdown .= "<option value='".$pro->product_name."'>".$pro->product_name."</option>";
        }
        //Categories drop down ends

        return view('students.add_student')->with(compact('products_dropdown'));
    }

As you can see the students are created and they save the email of who created them

Now on the index page, i would like the logged in user to see only his students.

First of all i create a foreach loop for students in index.blade.php

@foreach($students as $student)
                <!-- Item -->
                <div class="item">
                    <!-- Images -->
                    @if($student->student_sex == "M")
                    <img class="img-holder" src="{{asset('images/frontend_images/studente-M.jpg')}}" alt="" >
                    @else
                        <img class="img-holder" src="{{asset('images/frontend_images/studente-F.jpg')}}" alt="" >
                    @endif
                    <!-- Overlay  -->
                    <!-- Item Name -->
                    <div class="item-name"> <a href="#.">{{$student->student_name}} {{$student->student_surname}}</a>
                        <p>{{$student->codice_icf}}</p>
                    </div>
                </div>
            @endforeach

Where "$students" is defined in "IndexController" like this

<?php

namespace AppHttpControllers;

use AppCategory;
use AppProduct;
use AppStudent;
use Session;
use IlluminateHttpRequest;

class IndexController extends Controller
{


    public function index(){
        $students = Student::get();
        return view('index')->with(compact('students'));
    }
}

And the $student function in "StudentsController" like this:

<?php

namespace AppHttpControllers;

use AppStudent;
use AppProduct;
use Session;
use User;
use Auth;
use DB;
use IlluminateHttpRequest;
use function GuzzleHttpPromiseall;

class StudentsController extends Controller
{

 public function addStudent(Request $request){...}

 public function student(){
        if(Auth::check()){
            $user_email = Auth::user()->email;
            $students = DB::table('students')->where(['user_email'=>$user_email])->get();
        }
        return redirect('/')->with(compact('students'));
    }

As you can see the students appear on the index page, but if i log in with a different user they stay the same

This is my users controller, if you need the login function

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppUser;
use Auth;
use AppStudent;
use Session;
use DB;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesMail;

class UsersController extends Controller
{
    public function userRegister(){
        return view('users.register');
    }

    public function userLogin(){
        return view('users.login');
    }

    public function login(Request $request){
        if($request->isMethod('post')){
            $data = $request->all();
            if(Auth::attempt(['email'=>$data['email'],'password'=>$data['password']])){
                $userStatus = User::where('email',$data['email'])->first();
                if($userStatus->status == 0){
                    return redirect()->back()->with('flash_message_error', 'Il tuo  account non è attivo! Conferma la tua email per attivarlo.');
                }
                Session::put('frontSession',$data['email']);
                return redirect('/');
            }else{
                return redirect()->back()->with('flash_message_error', 'Email o Password errate!');
            }
        }
    }

    public function register(Request $request){
        if ($request->isMethod('post')) {
            $data = $request->all();
            //Check if User Already exist
            $usersCount = User::where('email', $data['email'])->count();
            if ($usersCount > 0) {
                return redirect()->back()->with('flash_message_error', 'Email già registrata!');
            } else {
                $user = new User;
                $user->name = $data['name'];
                $user->email = $data['email'];
                $user->password = bcrypt($data['password']);
                $user->save();

                // Send Confirmation Email
                $email = $data['email'];
                $messageData = ['email' => $data['email'],'name'=>$data['name'],'code'=>base64_encode($data['email'])];
                Mail::send('emails.confirmation',$messageData, function ($message) use($email){
                    $message->to($email)->subject('Conferma Account');
                });

                return redirect('/login')->with('flash_message_success', 'Perfavore conferma la tua email per attivare il tuo account!');

            }
        }
    }

    public function logout(){
        Auth::logout();
        Session::forget('frontSession');
        return redirect('/');
    }

    public function confirmAccount($email){
        $email = base64_decode($email);
        $userCount = User::where('email', $email)->count();
        if ($userCount > 0) {
            $userDetails = User::where('email', $email)->first();
            if ($userDetails->status == 1) {
                return redirect('/login')->with('flash_message_success', 'Il tuo account è già attivo! Effettua il login.');
            } else {
                User::where('email', $email)->update(['status' => 1]);
                //Welcome Email
                $messageData = ['email' => $email,'name'=>$userDetails->name];
                Mail::send('emails.welcome',$messageData, function ($message) use($email){
                    $message->to($email)->subject('Benvenuto!');
                });
                return redirect('/login')->with('flash_message_success', 'Il tuo account è stato attivato! Effettua il login adesso.');
            }
        }else{
            abort(404);
        }
    }

    public function checkEmail(Request $request)
    {
        $data = $request->all();
        $usersCount = User::where('email', $data['email'])->count();
        if ($usersCount > 0) {
            echo "false";
        } else {
            echo "true"; die;
        }
    }
}

How can I see for each different user only the students created by him using his email as a control field?
Thanks in advance!

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to Oleg Andreyev advice, i solved the problem by removing the function "student" in "StudentsController", so i delete this line:

     public function student(){
        if(Auth::check()){
            $user_email = Auth::user()->email;
            $students = DB::table('students')->where(['user_email'=>$user_email])->get();
        }
        return redirect('/')->with(compact('students'));
    }
    

    And i changed the "index" function to "IndexController" from this:

    public function index(){
        $students = Student::get();
        return view('index')->with(compact('students'));
    }
    

    To this one:

    public function index(){
        $students = Student::get();
        if(Auth::check()){
            $user_email = Auth::user()->email;
            $students = DB::table('students')->where(['user_email'=>$user_email])->get();
        }
        return view('index')->with(compact('students'));
    }
    

    And now i can see the students related to the email of the user who created them!


  2. It looks like you are doing a redirect to your IndexController

    return redirect('/')->with(compact('students'));
    

    You cannot redirect and pass some variable

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search