提问者:小点点

我想从Controller访问Laravel刀片文件中的一个对象的值


这是我的密码。 我正在尝试访问booknamebookauthor。 但变量是静态设置的。 我不想把这个改成公共的。 但我想访问这些值。 我怎么能做到呢?

<?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个答案

匿名用户

我建议您创建一个模型:php artisan make:model book-a,wit-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>

匿名用户

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;
    }

}

现在blade中的代码应该可以工作了:

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