I
I
Ilya Loopashko2021-03-24 06:53:06
Laravel
Ilya Loopashko, 2021-03-24 06:53:06

How to display the data of an authorized user from the database?

Good afternoon. I'm just learning how to use Laravel, don't kick too hard.

There are two tables in the database:
Users:
id: 1, name: Alex
id: 2, name: Ilya

Role:
id: 1, user_id: 2, title: user
id: 2, user_id: 1, title:

admin added:
$table->foreign('user_id')->references('id')->on('users');

After authorization, I need to display data from the database, in such images.

If logged in as Ilya then:
user ilya, role: user

and if as Alex then:
user Alex, role: admin

Here is what I could add to MainController so far

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MainController extends Controller
{
    public function index(Request $request)
    {
        $id = Auth::user()->id;
        $currentuser = User::find($id);

        return view('index', compact('currentuser'));
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
the5x, 2021-03-24
@deadloop

Make a role method in the model and get the data
User::with('role')->findOrFail($id);

I
Ilya Loopashko, 2021-03-24
@deadloop

How I implemented:

$id = Auth::user()->id;
$currentuser = User::find($id);
$user = $currentuser->name;
$role = Role::find($id);
$rolename = $role->title;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question