简体   繁体   中英

I want to access the values of an object to Laravel Blade file from Controller

Here is my code. I am trying to access the bookName and bookAuthor . But the variables are set in static. I don't want to change this to public. But I want to access those values. How can I do it?

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

I recommend you create a model: php artisan make:model Book -a, wiht -a will create you migration and controller apart from the model.

in your migration:

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

On your model:

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

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


}

On your controller:

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

}

On your blade:

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

}

now your code in blade should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM