Я хочу получить доступ к значениям объекта в Laravel Blade-файл из контроллера - PullRequest
0 голосов
/ 13 июля 2020

Вот мой код. Я пытаюсь получить доступ к bookName и bookAuthor. Но переменные устанавливаются в stati c. Я не хочу менять это на publi c. Но я хочу получить доступ к этим ценностям. Как это сделать?

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class Book
{
    private $bookName;
    private $bookAuthor;

    public function __construct($name, $author)
    {
        $this->bookName = $name;
        $this->bookAuthor = $author;
    }
    public function getNameAndAuthor()
    {
        return $this->bookName . ' - ' . $this->bookAuthor;
    }
}
class BookFactory
{
    public static function create($name, $author)
    {
        return new Book($name, $author);
    }
}

class FactoryController extends Controller
{
    public function index()
    {
        $book1 = BookFactory::create('Laravel', 'Imrul');
        $book2 = BookFactory::create('ReactJS', 'Hasan');

        $book1->getNameAndAuthor();
        $book2->getNameAndAuthor();
        // dump($book1);
        // dd($book1);
        return view('home', compact(['book1', 'book2']));
    }
}

home.blade.php

<h3>{{ $book1->bookName }}</h3>
<h3>{{ $book1->bookAuthor }}</h3>

Ответы [ 2 ]

0 голосов
/ 13 июля 2020
class Book
{
    private $bookName;
    private $bookAuthor;

public function __construct($name, $author)
{
    $this->bookName = $name;
    $this->bookAuthor = $author;
}
public function getNameAndAuthor()
{
    return $this->bookName . ' - ' . $this->bookAuthor;
}

 public function getBookNameAttribute()
    {
        return $this->bookName;
    }
 public function getBookAuthorAttribute()
    {
        return  $this->bookAuthor;
    }

}

теперь ваш код в клинке должен работать:

<h3>{{ $book1->bookName }}</h3>
<h3>{{ $book1->bookAuthor }}</h3>
0 голосов
/ 13 июля 2020

Я рекомендую вам создать модель: php artisan make: model Book -a, wiht -a создаст вам миграцию и контроллер отдельно от модели.

в вашей миграции:

public function up()
{
    Schema::table('books', function (Blueprint $table) {
        $table->increments('id');
        $table->string('author');
        $table->string('title');
    });
}

На вашей модели:

class Book extends Model
{
   protected $table = 'books';

   protected $fillable = [
   'author', 'title'
];


}

На вашем контроллере:

public function create()
{
    $book1 = Book::create([
        'author' => 'Henry',
        'title' => 'Smith',
    ]);
    $book2 = Book::create([
        'author' => 'Antony',
        'title' => 'Gjj',
    ]);
    return view('home', compact(['book1', 'book2']));

}

На вашем лезвии:

 <h3>{{ $book1->title }}</h3>
 <h3>{{ $book1->author }}</h3>
...