laravel 5 display books with author name - relationship

How do I display books with the author name?
Here is my model:
Book.php
public function authors()
{
return $this->belongsTo('App\Author');
}
Author.php
public function books()
{
return $this->hasMany('App\Book');
}
My controller:
BookController.php
use App\Author;
public function index()
{
foreach (Book::with('authors')->get() as $book)
{
echo $book->authors->name;
}
}
ERROR
Trying to get property of non-object
Please HELP what might be the problem?

Your code will display only author name for each book.
Instead use this code that returns all books with authors.
public function index()
{
$books = Book::with('author')->get();
return $books;
}

Related

how to use hasOne for two other detail models in laravel

I have one main table and two detail tables
table names: tb_main, tb_detail1, tb_detail2
tb_main
id, detail_code
tb_detail1
id, main_id
tb_detail2
id, main_id
I want get detail data using one function in main model
public function detail()
{
if(detail_code == 1)
return $this->hasOne(Detail1::class, 'main_id', 'id');
else
return $this->hasOne(Detail2::class, 'main_id', 'id');
}
Any ideas? please help me!
And sorry for my bad English.
You can use $this->detail_code
public function detail() {
if($this->detail_code == 1) {
return $this->hasOne(Detail1::class, 'main_id', 'id');
}else{
return $this->hasOne(Detail2::class, 'main_id', 'id');
}
Don't do that in the relation method. First, declare all relations in the main model like so:
public function detail1()
{
return $this->hasOne(Detail1::class, 'main_id');
}
public function detail2()
{
return $this->hasOne(Detail2::class, 'main_id');
}
Then write one method to decide what to do based on detail_code :
public function detail()
{
if($this->detail_code == 1)
return $this->detail1()->first();
return $this->detail2()->first();
}

Get posts by category's name in HomeController (Laravel 8)

To explain it in detail:
for example, i am creating posts with category, however i am saving it in a different table (post_categories), which means my posts and categories are connected through their IDs (belongToMany). Now in my HomeController i want to display posts, by the category name,
for example: $posts = post::where([['status',1],['category', 'electronics'])->orderBy('created_at', 'DESC')->limit(1)->get();
I want to display my posts by the Category-NAME and not Category-ID
I tried it but it doesnt really work, i guess i forgot something or I am using the wrong methode, pls help me
CODES
Home Controller
public function index()
{
$posts = post::where([['status',1],//here is category missing])->orderBy('created_at', 'DESC')->limit(1)->get();
$categories = Category::all();
return view('user.home', compact('posts', 'categories'));
}
public function category(category $category)
{
$posts = $category->posts();
return view('user.home',compact('posts'));
}
category Model
use HasFactory;
public function posts()
{
return $this->belongsToMany('App\Models\user\post','category_posts')->orderBy('created_at','DESC')->paginate(5);
}
public function getRouteKeyName()
{
return 'slug';
}
post Model
use HasFactory;
public function categories()
{
return $this->belongsToMany('App\Models\user\category','category_posts')->withTimestamps();;
}
public function getRouteKeyName()
{
return 'slug';
}
DATABASE
Posts_table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title',1000);
$table->string('subtitle',1000);
$table->string('slug',1000)->nullable();
$table->text('body');
$table->boolean('status')->nullable();
$table->integer('posted_by')->nullable();
$table->string('image')->nullable();
$table->timestamps();
});
}
Categories_table
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->timestamps();
});
}
category_posts
public function up()
{
Schema::create('category_posts', function (Blueprint $table) {
$table->unsignedBigInteger('post_id');
$table->unsignedInteger('category_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
}
public function index()
{
$posts = post::with('categories')->where([['status',1],//here is category missing])->orderBy('created_at', 'DESC')->limit(1)->get();
$categories = Category::all();// don't need this line if you don't need all categires
return view('user.home', compact('posts', 'categories'));
}
i already got the answer
i removed the relation and added location to a value in order to c

How to register afterMarshal in CakePHP 4.1

I noticed that there is new afterMarshal event in 4.1.
Where to put it? In Table model? And how?
I want to do some work with results every time it's loaded.
Thanks for help
For Encryption and Decryption through model in 'CAKEPHP 4'
public $encryptedFields = ['first_name','last_name'];
public function beforeSave($event, $entity, $options)
{
foreach($this->encryptedFields as $fieldName)
{ if($entity->has($fieldName))
{ $entity->set($fieldName, encodeBeforeSave($entity->get($fieldName)));}
} return true;
}
public function beforeFind( $event, $query, $options)
{ $query->formatResults(
function ($results)
{ return $results->map(function ($row){
foreach($this->encryptedFields as $fieldName)
{
if(isset($row[$fieldName]) && !empty($row[$fieldName]) )
{
$row[$fieldName] = decodeBeforefind($row[$fieldName]);
}
}
return $row;
});
}
);
}

Restriction on duplicate entry with respect to another column entry

I have two models Member and Saving with
Member('id','name')
Saving('id','member_id','amount','month')
I have to restrict duplicate entry of saving of a member for a given month.
Member.php
class Member extends Model
{
protected $fillable=['name','address','phone'];
public function loan()
{
return $this->hasOne(Loan::class,'member_id','id');
}
public function savings()
{
return $this->hasMany(Saving::class,'member_id','id');
}
}
Saving.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Saving extends Model
{
protected $fillable=['amount','month','member_id'];
public function member()
{
return $this->belongsTo('App\Member','member_id','id');
}
}
Is it possible to implement restriction, using functions in model, or controller?
EDIT:
this is how i tried.
SavingController.php
public function addSaving(Request $request){
if($request->isMethod('get')){
$memberData = Member::all();
return view($this->_pagePath.'saving.addsaving',compact('memberData'));
//return redirect()->back();
}
if($request->isMethod('post')){
$this->validate($request,[
'amount' => 'required',
'month' => 'required'
]);
$data['amount'] = $request->amount;
$data['month'] = $request->month;
$data['member_id']= $request->name;
$member= Member::find(1);
if($member->savings()->where('month',$request->month)->exists())
{
return 'Savings for this month are already added.';
}
else
{
if(DB::table('savings')->insert($data)){
return redirect()->route('saving')->with('success','data was successfuly inserted');
}
}
}
}
An enum is a wrong column for month my friend, unless you don't care for the year. Because this way you will just be able to store savings for each month, but not for each year separately.
Your relationship is set correctly, so you can then make a check like this:
// considering you have the specific member selected
$member = Member::find('ID_OF_THE_MEMBER');
if($member->savings()->where('month', APRIL)->exists())
{
return 'Savings for this month are already added.';
}

SessionComponent::setFlash

I'm using CakePHP 2.
This is my controller.
class GroupsController extends AppController {
public $helper = array('Html', 'Form', 'Session');
public function edit($id = null) {
if (empty($this->request->data)) {
$this->request->data = $this->Group->findByGroupId($id);
} else {
if($this->Group->save($this->request->data)) {
$this->Session.setFlash('Saved!!!');
$this->redirect(array('action' => 'index'));
}
}
}
}
When I pressed the save button on the page groups/edit/1, I got an error.
"Error: Call to undefined function setFlash()"
Fortunately, the changes I made were save to the database, I really don't get it, because setFlash() is a method of SessionComponent.
Please help, thanks.
Kongthap.
try this ::
$this->Session->setFlash('Saved!!!');

Resources