Home > Software design >  Define article id
Define article id

Time:10-07

I have a page of a separate article to which we go by slug

php.blade

@extends('layouts.app')

@section('content')

    <div class="article-wrapper">
        <div class="container">
            <h1>{{ $article->title }}</h1>
            <h3>{{ $article->subtitle }}</h3>
            <img src="{{ $article->main_image }}" alt="">
            <h3>{{ date('d F Y', strtotime($article->published_at)) }}</h3>
            <h3>{{ $article->views }} Views</h3>

            @foreach($article_blocks as $article_block)
            <div class="text-image">
                <h2>{{ $article_block->title_1 }}</h2>
                <h3>{{ $article_block->text_1 }}</h3>
                <img src="{{ $article_block->main_image }}" alt="">
            </div>
            @endforeach
@endsection

controller

public function index(Request $request, $slug)
    {
        $article = Article::where('slug', $slug)->first();

        $article_blocks = ArticleBlock::where('article_id', 1)->get();

        return view('article', compact('article', 'article_blocks'));
    }

Next, I have another model for blocks, each article has its own blocks, as you can see in my controller, I manually write the article ID to get the blocks specific for it.

How to make it itself determine which article we are on, and display blocks only for it?

CodePudding user response:

Try :

public function index(Request $request, $slug)
    {
        $article = Article::firstWhere('slug', $slug);

        $article_blocks = ArticleBlock::where('article_id', $article->id)->get();

        return view('article', compact('article', 'article_blocks'));
    }

If you have created relationships between your models, you can use it as follows:

public function index(Request $request, $slug)
        {
            $article = Article::with('articleBlock')->where('slug', $slug)->get();
    
            return view('article', compact('article'));
        }
  •  Tags:  
  • php
  • Related