Skip to content
Advertisement

Laravel (How do I add data to database)

Here’s my code that shows projects assigned to a user.

HomeController

public function index()
{
    $companies = auth()->user()->companies;
    $projects  = Project::whereIn('company_id',$companies->pluck('id'))->get();

    return view('home',compact('companies','projects'));
}

home.blade.php

@forelse($projects as $project)
    <a href="{{ route('issues.show', $project->id) }}" class="text-xl font-bold m-5 text-white">{{$project->title}}</a>
                
@empty
    <p>No Projects</p>
@endforelse

ProjectController that show issues within the project.

public function show($id){
      $project = Project::findOrFail($id);

    $issues = $project->issues;
    return view('issues', compact('issues', 'project'));
}

route:

Route::get('/issues/{id}', [AppHttpControllersProjectController::class, 'show'])->name('issues.show');

issues.blade.php

@forelse($issues as $issue)
    <a href="" class="text-xl font-bold m-5 text-white">{{$issue->title}}</a>
@empty
    <p>No Issues</p>
@endforelse

I made a button in the issues page that shows a modal that has a form for adding issues for the selected project. Can you help me with this? On how to do that?

Advertisement

Answer

Let’s imagine you have project controller like this.

public function show($id){
    $project = Project::findOrFail($id);

    return view('issues', compact('project'));
}

You don’ have to pass issues into blade. You can print it easily there.

Your blade

<table>
@foreach($project->issues as $issue)
   <tr>
      <td>{{ $issue->name }}</td>
   </tr>
@endforeach
</table>

Your form in your popup in blade

<form action="#" method="POST">
   <input name="project_id" type="hidden" value="{{ $project->id }}"/>
   <!-- all inputs you need -->
</form>

So what we did. You pasted the project id into form in hidden input. So now, after form submit you have in your backend input called project_id in your request.

In your issue controller

public function show(Request $request){
    dd($request->project_id); //there is your project_id 
}

Probably you have column project_id in your issues. So you can save it with $issue->associate($project_id). That’s just an example!!

I don’t know other fields you need to save with your issue, so I cannot help you more. I think you have got everything you needed to make a draft. 🙂

GL

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement