0
votes

I have updated my view for displaying data - projects, with AngularJS and now I have problem that when I change in URL address id of project, method show() didn't show 404 error - project does not belongs to logged in user, instead I'm getting this error.

Trying to get property of non-object (View: C:\www\htdocs\laravel\resources\views\backend\partials\project\single-project.blade.php)

Before I've updated my view to work with AngularJS everything was working fine.

My angular controller:

freelo.controller('mainCtrl', ['$scope', '$http', function($scope, $http) {

$scope.projects = [];
$http.get('api/userProjects')
    .then(function(response) {
        $scope.projects = response.data;
    });
}]);

My app.js:

var freelo = angular.module('freelo', []);

Method for retrieving user projects:

public function getProjectsInJson(){
    $project = Project::where('user_id', '=', $this->getCurrentUserId())->get();

    return response()->json($project);
}

And my show() method in ProjectsController:

public function show($id){
    $project = Project::where('id','=', $id)
                        ->where('user_id', '=', $this->getCurrentUserId())
                        ->first();
    $user = DB::table('projects')
        ->join('users', 'projects.user_id', '=', 'users.id')
        ->join('profiles', 'users.id', '=', 'profiles.user_id')
        ->select('users.id','profiles.username')
        ->where('projects.id','=', $id)
        ->get();

    if(!$project && !$user){
        abort(404);
    }else{
        return view('backend.partials.project.single-project')->with('project', $project)->with('user', $user);
    }
}

Where did I make mistake or what must be changed?

1

1 Answers

1
votes
  public function show($id){
    try{
        $project = Project::where('id','=', $id)
              ->where('user_id', '=', $this->getCurrentUserId())
              ->with(['user', 'user.profile'])
              ->firstOrFail();
    }catch(\ModelNotFoundException $e){
        abort(404);
    }    

    return view('backend.partials.project.single-project')->with('project', $project);
  }

Project model would be like

public function user()
{
 return $this->belongsTo('\User', 'user_id');
}

User model:

public function profile()
{
 return $this->hasOne('\Profile', 'user_id', 'id');
}

Try this one