1

I have two tables.users and company. i am using auth for login and registration. and i used user_id from users table as a foreign key in company table. To store user_id from session i used hidden input field.

@if (Auth::user())
   <input type="hidden" class="form-control" name="userid" value="{{ @Auth::user()->id }}">
@endif

query for insert data in company table.

public function insert(Request $request)
    {
        $name = $request->input('username');
        $id = $request->input('userid');
        DB::table('company')->insert(
        ['com_name' => $name,'id' => $id]

        );
      return view('home');

    }

Now, User will login himself and create multiple companies.Next time when he will login he can see only list of his companies.

In current scenario i have this query but its not worth to used.

public function show(Request $request)
    {
        $companies = DB::table('company')->where('id', 1)->get();

        return view('dashboard', ['users' => $companies]);
    }

1 Answer 1

0

You need to change id to user_id here:

DB::table('company')->insert(['com_name' => $name, 'user_id' => $id]);

And here:

$companies = DB::table('company')->where('user_id', auth()->id())->get();

Alternatively, you could just do this:

$companies = auth()->user()->companies()->get();
Sign up to request clarification or add additional context in comments.

8 Comments

$companies = DB::table('company')->where('user_id', 1)->get(); it will display only user_id 1's data. and what if user_id 2 is logged in
I'm sorry, I thought it's obvious and copy pasted 1 from you code. You should use auth()->id() instead of 1.
$companies = DB::table('company')->where('id', auth()->id())->get(); i used this n i get all companies from table
Use my query instead of yours. It should be user_id, not id.
bro still i get all values from db. i used your code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.