我想从控制器访问 Laravel Blade 文件的对象值

这是我的代码。我正在尝试访问bookName和bookAuthor。但变量是静态设置的。我不想将其更改为公开。但我想访问这些值。我该怎么做?


<?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>


斯蒂芬大帝
浏览 131回答 2
2回答

翻阅古今

我建议您创建一个模型: php artisan make:model Book -a,其中 -a 将为您创建除模型之外的迁移和控制器。在您的迁移中:public function up(){&nbsp; &nbsp; Schema::table('books', function (Blueprint $table) {&nbsp; &nbsp; &nbsp; &nbsp; $table->increments('id');&nbsp; &nbsp; &nbsp; &nbsp; $table->string('author');&nbsp; &nbsp; &nbsp; &nbsp; $table->string('title');&nbsp; &nbsp; });}在你的模型上:class Book extends Model{&nbsp; &nbsp;protected $table = 'books';&nbsp; &nbsp;protected $fillable = [&nbsp; &nbsp;'author', 'title'];}在您的控制器上:public function create(){&nbsp; &nbsp; $book1 = Book::create([&nbsp; &nbsp; &nbsp; &nbsp; 'author' => 'Henry',&nbsp; &nbsp; &nbsp; &nbsp; 'title' => 'Smith',&nbsp; &nbsp; ]);&nbsp; &nbsp; $book2 = Book::create([&nbsp; &nbsp; &nbsp; &nbsp; 'author' => 'Antony',&nbsp; &nbsp; &nbsp; &nbsp; 'title' => 'Gjj',&nbsp; &nbsp; ]);&nbsp; &nbsp; return view('home', compact(['book1', 'book2']));}在你的刀片上:&nbsp;<h3>{{ $book1->title }}</h3>&nbsp;<h3>{{ $book1->author }}</h3>

饮歌长啸

class Book{&nbsp; &nbsp; private $bookName;&nbsp; &nbsp; private $bookAuthor;public function __construct($name, $author){&nbsp; &nbsp; $this->bookName = $name;&nbsp; &nbsp; $this->bookAuthor = $author;}public function getNameAndAuthor(){&nbsp; &nbsp; return $this->bookName . ' - ' . $this->bookAuthor;}&nbsp;public function getBookNameAttribute()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->bookName;&nbsp; &nbsp; }&nbsp;public function getBookAuthorAttribute()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; $this->bookAuthor;&nbsp; &nbsp; }}现在刀片中的代码应该可以工作:<h3>{{ $book1->bookName }}</h3><h3>{{ $book1->bookAuthor }}</h3>
打开App,查看更多内容
随时随地看视频慕课网APP