我正在尝试获取特定的列数据,并通过if语句运行它来检查状态是否得到确认,但出现“尝试获取非对象的属性'status'状态”错误
这是我的控制者;
public function transaction(Request $request){
request()->validate([
'amount' => 'required'
]);
$trans = Transaction::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->first();
if(Auth::user()->transaction && !$trans->status){
return redirect()->back()->with("error", "You currently have a withdrawal request pending confirmation");
}
if($request->input('amount') > Auth::user()->balance){
return redirect()->back()->with("error", "Insufficient balance to complete request");
}
Mail::to('mail@gmail.com')->send(new transaction($request));
$transaction->save();
return redirect()->back()->with("success", "Your withdrawal request has successfully been received");
}
我的交易模型;
namespace App;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo('App\User');
}
}
答案 0 :(得分:0)
首先,您需要检查记录是否存在。 在访问对象的status属性之前,请使用以下代码,并确认您已从数据库接收数据。
if(!$trans) {
return abort(404); // record does not exists
}
错误的原因是查询未返回数据。 $ trans变量包含空值,这就是您收到错误试图获取非对象的属性“状态”的原因。
答案 1 :(得分:0)
您应该检查$ trans对象是否存在。 将您的代码更改为此:
if(empty($trans) || (Auth::user()->transaction && !$trans->status)) {
return redirect()->back()->with("error", "You currently have a withdrawal request pending confirmation");
}
答案 2 :(得分:0)
此行之后
$trans = Transaction::where('user_id', Auth::user()->id)->orderBy('id', 'desc')->first();
检查这个
`if($ trans ==''|| $ trans == null){
返回redirect()-> back()-> with(“错误”,“没有可用的跨栏”);
}