Skip to content Skip to sidebar Skip to footer

Acces To Data Using Relationships Laravel

i want to access to data in the function of the controller using relationships on Laravel. I will explain first my code: I have 3 tables, projects, client and client_project. At t

Solution 1:

Here is your ans. You are going good way you created pivot table for client and project so you can attached as many projects to any client. Here is relationship with model.

Client Model

<?phpnamespaceApp\Models;

useIlluminate\Database\Eloquent\Model;

classClientextendsModel{
    publicfunctionprojects() {
        return$this->belongsToMany(Project::class,'client_project');
    } 
}   

Project model

<?phpnamespaceApp\Models;

useIlluminate\Database\Eloquent\Model;

classProjectsextendsModel{



    publicfunctionclient() {
        return$this->belongsToMany(Client::class,'client_project');
    } 


}   

?>

For Save project id use following way in controller method

$client = new Client();
    $client->name = $request->input("nameClient");
    $client->slug = $request->input("slugClient");
    $client->priority = $request->input("priorityClient");
    $client->save();
    $project = new Project();
//include fields as per your table $project->save();

    $client->projects()->attach($project->id);

.

Post a Comment for "Acces To Data Using Relationships Laravel"