如何修改我的 Controller 以便查询仅限于用户 ID?
How can I modify my Controller so that the query is limited to the user id?
我的控制器是这样设置的:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Booking;
class eventController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$events = array();
$bookings = Booking::all();
foreach($bookings as $booking) {
'id' => $booking->id,
'title' => $booking->title,
'resourceId' => $booking->resourceId,
'start' => $booking->start_date,
'end' => $booking->end_date,
];
}
return view('home', ['events' => $events]);
}
}
在这里我可以将我的数据库中的所有内容传递到我的视图中,但是我如何过滤掉这些内容以便只显示来自某个 user_id 的条目?这就是我的 table 的样子:https://imgur.com/AUZhA1L.
我曾尝试使用{user} blade,但卡住了。
更改此行:
$bookings = Booking::all();
对此:
$bookings = Booking::where('user_id', 9)->get();
或者如果你想获取登录用户,你可以使用Auth
。
在use App\Models\Booking;
之后添加这一行
use Illuminate\Support\Facades\Auth;
然后:
$bookings = Booking::where('user_id', Auth::id())->get();
在您的用户模型中添加以下功能(一个用户可能有很多预订)
public function bookings(){
return $this->hasMany(Booking::class);
}
调用Auth::user()获取登录用户;
喜欢
$user = Auth::user();
$bookings = $user->bookings();
我的控制器是这样设置的:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Booking;
class eventController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$events = array();
$bookings = Booking::all();
foreach($bookings as $booking) {
'id' => $booking->id,
'title' => $booking->title,
'resourceId' => $booking->resourceId,
'start' => $booking->start_date,
'end' => $booking->end_date,
];
}
return view('home', ['events' => $events]);
}
}
在这里我可以将我的数据库中的所有内容传递到我的视图中,但是我如何过滤掉这些内容以便只显示来自某个 user_id 的条目?这就是我的 table 的样子:https://imgur.com/AUZhA1L.
我曾尝试使用{user} blade,但卡住了。
更改此行:
$bookings = Booking::all();
对此:
$bookings = Booking::where('user_id', 9)->get();
或者如果你想获取登录用户,你可以使用Auth
。
在use App\Models\Booking;
use Illuminate\Support\Facades\Auth;
然后:
$bookings = Booking::where('user_id', Auth::id())->get();
在您的用户模型中添加以下功能(一个用户可能有很多预订)
public function bookings(){
return $this->hasMany(Booking::class);
}
调用Auth::user()获取登录用户; 喜欢
$user = Auth::user();
$bookings = $user->bookings();