无法通过中间件过滤请求



我正在尝试使用中间件过滤我的http请求。
我想检查我从 http 请求获得的"friends_id">和我通过 Auth 传入的"my_id">是否已经不在同一行中存在,如果他们这样做,我想重定向到主页,如果他们不这样做,我想执行正常请求,最终将插入我正在检查
的数据

错误是"尝试获取非对象的属性'friends_id'">

这是我的"朋友"中间件:-

<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesDB;
class Friends
{
public function handle($request, Closure $next)
{  $auth = Auth()->user()->id;
$dost = $request->friends_id;
$ip = DB::table('friends')
->where('my_id', '=', $auth)
->where('friends_id', '=', $dost)
->get();
if($ip->friends_id != $dost){
return $next($request);
}

return redirect('/home');
}
}

这是我的朋友表:-

public function up()
{
Schema::create('friends', function (Blueprint $table) {
$table->id();
$table->string('my_id');
$table->string('friends_id');
$table->string('name');     
$table->timestamps();
});
}

这是我的路线:-

Route::post('/f', 'FriendsController@store')->middleware('friends');

-谢谢

试试这个

您的查询将错误地使用where而不是whereColumn并且当您获得第一条记录时,仅使用first()而不使用get()

use DB;
$ip = DB::table('friends')
->select('my_id', 'friends_id')
->where([['my_id', '=', '$auth'],['friends_id', '=', '$dost']])
->first();

编辑

public function handle($request, Closure $next)
{  
$auth = Auth()->user()->id;
$dost = $request->friends_id;
$ip = DB::table('friends')
->select('my_id', 'friends_id')
->where([['my_id', '=', '$auth'],['friends_id', '=', '$dost']])
->first();
if($ip->friends_id == $dost){
return redirect('/home');
} else {
return $next($request);
}
}

解决方案是:-

朋友中间件:-

public function handle($request, Closure $next)
{
if (auth()->check()) {
$ip = DB::table('friends')->where('my_id', '=', auth()->id())->where('friends_id', '=', $request->friends_id)->first();
if ($ip && $ip->friends_id == $request->friends_id) {
return redirect('/home');
}
}
return $next($request);
}
}

最新更新