Home > Back-end >  Method Illuminate\Http\Request::company does not exist
Method Illuminate\Http\Request::company does not exist

Time:05-19

am trying to make Agents(users) create posts and save it to the database . I have created model for Posts and Agents with two functions company and posts and am trying to access those functions in the Post Controller but it gives me error.Thanks in advance Here is my post model code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    public function company(){
        return $this->belongsto(Agent::class);
    }
}

and my agent model code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Agent extends Model
{
    use HasFactory;
    public function posts(){
        return $this->hasMany(Post::class);
    }
}

controller code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    //
    function postform(){
        return view('createposts');
    }
    function createpost(Request $request){
        $post = new Post ;
        $post->title = $request->job_title;
        $post->description = $request->job_description;
        $post->type = $request->type;
        $request->company()->posts()->save($post);
    }
}

the error is in this line $request->company()->posts()->save($post);

CodePudding user response:

Request doesn't have company() method. Apparently it's a method of post. You can save directly de $post->save(). Or maybe asociate de company to de post doing $post->company = request()->company; and then save it.

CodePudding user response:

Yes, of course - Illuminate\Http\Request doesn't have company() method (*unless you have extended the class or used a macro).

Hard to guess the intent; are you trying to attach the new Post to an Agent who created it?

In which case where does the Agent come from?

  • Related