Search code examples
phplaravellaravel-4relationships

laravel 4 how to retrieve logged in users data


I'm a real newbie to Laravel but I'm loving it so far. I'm struggling on thing however, I want to retrieve the data for the user that is logged in and I am not sure how to go about this.

I have a few tables but I'll keep it basic for now, I have projects table and a users table, I've defined the relationships between these two in the models as so:

user.php

public function projects() {
    return hasMany('project');

}

project.php

<?php
use Illuminate\Database\Eloquent\ModelNotFoundException;

class Project extends Eloquent
{
    public function user()
    {
        return belongsTo('user');
    }
}

I know I can do the following to retrieve all projects in the database with a foreach loop, however this doesn't retrieve the logged in users projects:

$projects = DB::table('projects')->get();

I saw one tutorial which wasn't very in depth but he said to access the model query I would have to use the following command:

$project = User::all()->projects; 

However this hasn't worked either. Can anyone point me into the right direction with real tutorials or post simple examples?

Thanks in advance


Solution

  • Those are the projects of your logged in user:

    if (Auth::check())
    {
        $projects = Auth::user()->projects;
    }
    

    And this must be in your relation:

    class User extends Eloquent
    {
        public function projects() {
    
            return this->hasMany('Project');
    
        }
    }
    

    You also need to add $this to your Project relation:

    class Project extends Eloquent
    {
        public function user()
        {
            return $this->belongsTo('User');
        }
    }