A
A
Alfieros2021-04-28 14:23:52
Laravel
Alfieros, 2021-04-28 14:23:52

How to get the ID and title of the category when creating a post?

Hello! Question on Laravel 7.
There is a user with the ability to create their own unique categories for publishing posts in them. Can't implement the following.

The user goes to the general list of their rubrics, where each rubric has a "Create Post" button. You need to get the ID of this very category on the post creation page.

Models and tables are interconnected (one to all), all this data exists in the array, but it is not possible to assign the ID of a specific category, within which the click was made. Accordingly, the user still has a drop-down list of his headings, instead of the one needed.

For example, if you write "Create Post" buttons in the route - route('user.post.create', ['rubric' -> $rubrics->id]), then the ID of this category is transmitted in the URL. But how to get this ID inside the form, I can not find a solution. Tell me in which direction to swim, or can there be a simple solution? I didn’t find answers in Google, since this is not quite a standard question for laravel, I find it difficult even to formulate it correctly.

Record Controller

public function create() {
    $users = Auth::user()->id;
    $rubrics = Rubric::where('user_id', '=', $users)->get(); //здесь я получаю список всех рубрик этого юзера.

    return view('user.post.create', compact('rubrics'));
}

Record Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Stem\LinguaStemRu;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\SoftDeletes;
use Iatstuti\Database\Support\CascadeSoftDeletes;

class Post extends Model {

protected $fillable = [
    'category_id',
    'user_id',
    'rubric_id',
    'name',
    'slug',
    'content',
    'image',
];

public function category() {
    return $this->belongsTo(Category::class);
}

public function rubric() {
    return $this->belongsTo(Rubric::class);
}


Here is an example of what I want to do in images.
Category list page:
60894f5b95bb9870671787.png
Post creation page:
60894f751f1f8287903909.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-05-11
@dlnsk

Each "Create Post" button should be inside a separate form, insert a hidden input with the category id into each such form. This is if you want to use POST.
You can, as you wrote, with route('user.post.create', ['rubric' -> $rubrics->id]). The essence is the same.
The main thing:
In the controller method that returns the form, get the category id and pass it as a hidden input to the form itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question