So I'm new to laravel and I'm trying to figure out a way to connect my database with my front end!
First this is the villa model for the table villas:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Villa extends Model
{
use HasFactory;
protected $fillable=[
"id", "title", "description", "price", "state", "status", "city_id", "seller_id", "payment_id", "created_at", "updated_at"
];
public function City()
{
return $this -> hasOne(City::class,'id','city_id');
}
public function Seller()
{
return $this -> hasOne(Seller::class,'id','seller_id');
}
public function Payment()
{
return $this -> hasOne(Payment::class,'id','payment_id');
}
}
this is the website controller : and here I'm trying to call the table
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Villa;
use App\Models\City;
use App\Models\VillaImg;
class WebsiteController extends Controller
{
public function index(){
$villas = DB::select('select * from villas');
return view('website',['villas'=>$villas]);
}
this is the website blade which I use this way to call the value but I don't know how to call a foreign key value , for example : I have the foreign key city_id and I want the show the city name on my front end but don't know how
@foreach ($villas as $user)
<a href="single-villa.html" id="villaname">{{old('name',$user->title )}}</a>
@endforeach
@foreach ($villas as $user)
<a href="#" id="villaLocation">{{old('city',$user->I don't know what to write here)}}</a>
@endforeach
Note: this is a code in a div that represents a villa block. Also, I'm not sure if this is really the correct way to do so and I want to know if there's another efficient way to do that!
here's the route:
Route::get('/',[WebsiteController::class,'index'])->name('home.index');
CodePudding user response:
use eloquent orm instead of db facade...
$villas = Villa::with(['City', 'Seller', 'Payment'])->get();
and then if u need any relation value:
@foreach ($villas as $villa)
{{ $villa->City->property }}
@endforeach