Caio Kawasaki Caio Kawasaki - 4 months ago 18
PHP Question

Get all data from pivot table

By now, I can get the data in the pivot table, but my question is, how can I get all the categories from my categories table and, if exists this category in my pivot table the input needs to be checked, how can I get this?

Project model

class Project extends Model
{
protected $table = 'projects';

protected $fillable = [
'name',
'slug',
'header',
'desc',
'about',
'url',
'status'
];

public function customer()
{
return $this->belongsTo(Customer::class);
}

public function category()
{
return $this->belongsToMany(Category::class)->withPivot('category_id');
}
}


Category model

class Category extends Model
{
protected $table = 'categories';

protected $fillable = [
'name',
'status'
];

public function user()
{
return $this->belongsTo(User::class);
}

public function subCategory()
{
return $this->hasMany(SubCategory::class);
}

public function projects()
{
return $this->belongsToMany(Project::class)->withPivot('project_id');
}
}


Controller

public function getEdit(Customer $customer, $project)
{
return view('admin.pages.admin.clientes.projetos.edit', [
'customer' => $customer,
'project' => Project::where('id', $project)->firstOrFail(),
'categories' => $this->categoryRepository->allCategories(), //return all categories in the categories table
'title' => $customer->name
]);
}


Form

{!! Form::model($project, ['class' => 's-form', 'route' => ['project.update', $customer->id, $project->id]]) !!}
{{ method_field('PUT') }}
<div class="s-form-item text">
<div class="item-title required">Nome do projeto</div>
{!! Form::text('name', null, ['placeholder' => 'Nome do projeto']) !!}
@if($errors->has('name'))
<div class="item-desc">{{ $errors->first('name') }}</div>
@endif
</div>
<div class="s-form-item text">
<div class="item-title">Descrição do projeto</div>
{!! Form::text('desc', null, ['placeholder' => 'Descrição do projeto']) !!}
@if($errors->has('desc'))
<div class="item-desc">{{ $errors->first('desc') }}</div>
@endif
</div>
<div class="s-form-item text">
<div class="item-title">Sobre o projeto</div>
{!! Form::text('about', null, ['placeholder' => 'Sobre o projeto']) !!}
@if($errors->has('about'))
<div class="item-desc">{{ $errors->first('about') }}</div>
@endif
</div>
<div class="s-form-item text">
<div class="item-title">URL do projeto</div>
{!! Form::text('url', null, ['placeholder' => 'URL do projeto']) !!}
@if($errors->has('url'))
<div class="item-desc">{{ $errors->first('url') }}</div>
@endif
</div>
<div class="s-form-item text">
<div class="item-title">Imagem de cabeçalho do projeto</div>
{!! Form::text('header', null, ['placeholder' => 'Imagem de cabeçalho do projeto']) !!}
@if($errors->has('header'))
<div class="item-desc">{{ $errors->first('header') }}</div>
@endif
</div>
<div class="s-form-item checkbox inline">
<div class="item-title">Categorias do projeto</div>
@foreach($project->category as $category)
{{-- Here I get all the categories, and the categories that exists in the pivot table will be checked--}}
{{--<div class="s-checkbox s-radio-input">--}}
{{--<input id="category-{{ str_slug($category->name) }}" type="checkbox" name="categories[]" value="{{ $category->id }}">--}}
{{--<label for="category-{{ str_slug($category->name) }}"><span></span>{{ $category->name }}</label>--}}
{{--</div>--}}
@endforeach
</div>
<div class="s-form-item radio inline">
<div class="item-title required">Status do projeto</div>
<div class="s-radio-input">
{!! Form::radio('status', '1', null, ['id' => 'categoria-ativo']) !!}
<label for="categoria-ativo"><span></span>Ativa</label>
</div>
<div class="s-radio-input">
{!! Form::radio('status', '0', null, ['id' => 'categoria-inativo']) !!}
<label for="categoria-inativo"><span></span>Inativa</label>
</div>
</div>
<div class="s-form-item s-btn-group s-btns-right">
<a href="{{ url('admin/clientes/editar') . '/' . $customer->id }}" class="s-btn cancel">Voltar</a>
<input class="s-btn" type="submit" value="Atualizar">
</div>
{!! Form::close() !!}

Answer

In your controller you need to select the project with its categories:

public function getEdit(Customer $customer, $project)
{
    return view('admin.pages.admin.clientes.projetos.edit', [
        'customer' => $customer,
        'project' => Project::with('category')->findOrFail($project),
        'categories' => $this->categoryRepository->allCategories(), //return all categories in the categories table
        'title' => $customer->name
    ]);
}

Then in your HTML:

<div class="s-form-item checkbox inline">
    <div class="item-title">Categorias do projeto</div>
    @foreach($categories as $category)
        <div class="s-checkbox s-radio-input">
            <input id="category-{{ str_slug($category->name) }}" type="checkbox" name="categories[]" {{$project->category->contains($category) ?  'checked="true"' : ''}} value="{{ $category->id }}">
            <label for="category-{{ str_slug($category->name) }}"><span></span>{{ $category->name }}</label>
        </div>
    @endforeach
</div>

The update the Project with the selected categories:

$project = Project::findOrFail($project);
$project->category()->sync($request->input('categories', []));
$project->update($request->except(['_token','_method', 'categories']);

I hope this will help you.

Comments