首页 > 解决方案 > Angular - “类 Illuminate\Database\Eloquent\Builder 的对象无法转换为字符串

问题描述

我正在开发一个以 Angular 7 作为前端,Laravel 5.8 作为后端的项目。我想要的是,当 id = 1 的用户(管理员)登录时,他会看到一切。但是当其他用户登录时,他只能看到具有他的 user_id 的数据。

Laravel:后端

   public function indexSmsmo()
{
if(Auth::user()->id == 1)
     $smsmos = Smsmo::all();
else 
 $smsmos = Smsmo::where('user_id',Auth::user()->id);
return $smsmos;               
}

我有用户表和其他表。其他表中有 user_id。

auth.service.ts

import { environment } from '../../environments/environment.prod';
import { User } from '../models/user';

@Injectable({
providedIn: 'root'
})
export class AuthService {

public currentUser: User;
private readonly apiUrl = environment.apiUrl;
private environmentService: EnvironmentService;

constructor(
private http: HttpClient,
private router: Router) 
{     
}

onLogin(user: User): Observable<User> {

const request = JSON.stringify(
  { email: user.email, password: user.password }
);

return this.http.post(this.loginUrl, request, httpOptions)
  .pipe(
   map((response: User) => {
  // Receive jwt token in the response
  const token: string = response['access_token'];
  // If we have a token, proceed
  if (token) {
    this.setToken(token);
    this.getUser().subscribe();
  }
  return response;
  }),
  catchError(error => this.handleError(error))
   );
  }

在此之后我们有登录组件

登录组件.ts

  ngOnInit() {
  document.body.className = 'hold-transition login-page';
  $(() => {
  $('input').iCheck({
   checkboxClass: 'icheckbox_square-blue',
   radioClass: 'iradio_square-blue',
   increaseArea: '20%' /* optional */
  });
});

//  Set the return url
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/home';
this.authService.onLogout();
}

onSubmit(loginForm): void {
this.spinnerService.show();
this.authService.onLogin(this.user).subscribe(
  (response) => {      

this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})        
this.router.navigate([this.returnUrl]);       
},
(error) => {
this.spinnerService.hide();
this.error = error.error;
}
);
 // Clear form fields
 loginForm.reset();
 }  

当我使用 userId 1 登录时,一切正常。但是当我使用其他 userId 登录时,我遇到了这个错误:

httpErrorResponse 消息:“类 Illuminate\Database\Eloquent\Builder 的对象无法转换为字符串

如果用户登录并且 user_id 为 1,他应该看到所有内容,但如果不是 1,他应该看到 user_id 等于登录 ID 的数据

我该如何解决这个问题?

标签: angularlaravelapi

解决方案


在您的index方法中,如果 user is id === 1,您将返回一个集合,因为您使用了all().

如果用户不是id === 1,则您仅返回一个构建器对象,因为您没有完成查询:

$smsmos = Smsmo::where('user_id',Auth::user()->id);

应该

$smsmos = Smsmo::where('user_id',Auth::user()->id)->first(); // or get() if you want a collection

推荐阅读