Domanda

Trying to retrieve the users firstname from the Users table when they submit a post and insert there firstname into the Posts table under the field author. I don't think i'm going about it correctly though.

Post Model

 public function insertPost($input)
{
    $validation = new Services\Validators\Post;

    if ($validation->passes())
    {
        $post = Post::create($input);

        // Get the logged in user from the users table and save it to the posts table author field
        $name = Post::get()->user->firstname;

        $author = $input['author'];
        $post->author = $name;
        $post->save();

    }

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

User Model (relationship defined to Post model)

public function posts()
{
    return $this->hasMany('Post', 'author');
}
È stato utile?

Soluzione

You can try this (Only logged in user can submit a post, so get the name from logged in user object):

if ($validation->passes())
{
    $name = Auth::user()->firstname; // Get logged in user's first name
    $input = array_merge(array('author' => $name), $input);
    return $post = Post::create($input);
}

Also you can create new post like this:

$post = new Post;
$post->title = Input::get('title'); // or $input[['title'] if $input is available
$post->author = Auth::user()->firstname;
// ... do same for all fields, assign values to each field, then save
return  $post->save();

Altri suggerimenti

You are trying to instantiate Post::create . If you want instance of Post model you should:

$post = new Post

Also see did you actually provided Post model to User ?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top