PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 29, 2021

[FIXED] How to get the username through an id in Laravel?

 December 29, 2021     laravel, php, phpmyadmin     No comments   

Issue

I am trying to create an offers forum, where some user can create their offers in order to provide their services and I want to show the name of the person that created that offer instead of the id.

In my database I have the two tables:

  • Offers table: Offers table

  • User table:

Users table

In offers I have a column of the professor_id, that is related to the id of users table.

This is what i have in my controller to show the offers:

public function ofertes(){

    $ofertes = Oferta::all()->sortByDesc('id');

    return view('create.ofertes')->with(compact('ofertes'));
}

and in the blade.php I have that code:

@foreach($ofertes as $oferta)
    <tr>
        <td>Nom : {{$oferta->professor_id}}</td> <br>
        <td>Títol : {{$oferta->titol}}</td> <br>
        <td>Descripció: {{$oferta->descripcio}}</td> <br>
        <td>Data: {{$oferta->created_at}}</td> <br><br>
    </tr>
@endforeach

and that is what is shown: ofertes.blade.php

Where it says nom, how I can show the name instead of the id?

Thank you!


Solution

If you have specified the relationship to professor in your Oferta model you can use the following code:

public function ofertes(){

    $ofertes = Oferta::with('professor')->latest()->get();

    return view('create.ofertes')->with(compact('ofertes'));
}

Your blade:

@foreach($ofertes as $oferta)
    <tr>
        <td>Nom : {{$oferta->professor->nom}}</td> <br>
        <td>Títol : {{$oferta->titol}}</td> <br>
        <td>Descripció: {{$oferta->descripcio}}</td> <br>
        <td>Data: {{$oferta->created_at}}</td> <br><br>
    </tr>
@endforeach

If you haven't specified the relation you should add the following method to your Oferta model (you might need to tweak this a little bit based on your namespaces):

public function professor()
{
    return $this->belongsTo(User::class);
}


Answered By - Dees Oomens
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing