I am trying to use (and get my head around Eloquent) to get a username from the user table, based on the user_id I have stored in another table, but everything I try seems to be throwing up road blocks. I've tried a loop (foreach) and then using what I thought was the correct syntax for Eloquent to get what I need, but it's not working. I've done this using views before and it works, but doesn't work in the Controller.
Hoping someone here can show me how this is supposed to work, based on my code.
Lead Model:
class Lead extends Model
{
protected $fillable = [
'bname', 'tname'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
LeadController
class LeadController extends Controller
{
use Helpers;
public function index(Lead $leads)
{
$leads = $leads->get();
//foreach $leads, get the username from 'user_id' from user table
//return the leads, without the user_id, but with the username
return $leads;
}
}
Function in User.php (class User extends Authenticatable)
public function leads()
{
return $this->hasMany(Lead::class);
}
Lead Migration
Schema::create('leads', function (Blueprint $table) {
$table->increments('lead_id')->nullable(false);
$table->string('bname')->nullable(false);
$table->string('tname')->nullable();
$table->integer('user_id')->index();
$table->timestamps();
});
Hopefully this makes sense to you and someone can help me learn :)
Thanks.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire