posts and attachments, Undefined property: Illuminate\Database\Eloquent\Collection::$name - laravel-4

when i try to get the attachment's name like this:
{{$post->attachments->name}}
i get the following error
Undefined property: Illuminate\Database\Eloquent\Collection::$name (View: C:\wamp\www\Sites\app\views\public\categories\show.blade.php)
Post model
class Post extends \Eloquent implements SluggableInterface {
public function category(){
return $this->belongsTo('Category');
}
public function attachments(){
return $this->hasMany('Attachment');
}
}
Attachment Model
class Attachment extends \Eloquent {
protected $fillable = ['name', 'type', 'extension', 'user_id', 'post_id', 'size'];
public function post(){
return $this->belongsTo('Post');
}
}
CategoriesController
class CategoriesController extends \BaseController {
public function show($id, $slug = null)
{
$category = Category::find($id);
$posts = Post::whereCategoryId($category->id)->orderBy('date', 'DESC')->paginate(4);
return View::make('public.categories.show', compact('category', 'posts'));
}
}
categorie View
#foreach($posts as $post)
{{$post->title}} // work fine
{{$post->body}} // work fine
{{$post->attachments}} // return this :
[
{
"id":14,
"name":"29-01-2015-134",
"type":"image\/jpeg",
"extension":"jpg",
"created_at":"2015-01-29 13:04:35",
"updated_at":"2015-01-29 13:04:35",
"user_id":1,
"post_id":134,
"size":136130
}
]
#endforeach
any ideas?!!!

According to your relationship definition there can be many attachments, that means the relation will return a collection of models. You can either get only the first one:
#if($attachment = $post->attachments()->first())
{{ $attachment->name }}
#endif
Or loop over all attachments
#foreach($post->attachments as $attachment)
{{ $attachment->name }}
#endforeach

Related

Blank object in Eloquent belongsTo()

I'm trying to display which one attribute (code) of Item. ServiceItem has Item as a foreign key. But I can't get the Item at all.
This one gives a blank object in blade template:
#foreach ($service->serviceItems as $serviceItem )
{{ json_encode($serviceItem->item()) }}
#endforeach
Here's my model declaration:
//ServiceItem model
class ServiceItem extends Model
{
use HasFactory;
public $fillable = ['service_id', 'item_id', 'values'];
public function service()
{
return $this->belongsTo(Service::class, 'foreign_key');
}
// this doesn't work
public function item()
{
return $this->belongsTo(Item::class, 'foreign_key');
}
}
// Service model
class Service extends Model
{
use HasFactory;
public $fillable = ['user_id', 'site_id', 'title', 'status', 'remarks', 'report', 'date'];
public function user()
{
return $this->belongsTo('\App\Models\User');
}
public function site()
{
return $this->belongsTo('\App\Models\Site');
}
public function serviceItems() {
return $this->hasMany('\App\Models\ServiceItem');
}
}
This is my controller:
public function index()
{
$services = Service::latest()->paginate(5);
return view('services.index', compact('services'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
Please help me to display the code attribute in Item from Service!!! Thanks a lot!
I suppose you read the Laravel doc of model relationship definition. They referenced to put foreign key as the second parameter, not the foreign_key as word but your actual foreign key that reference the parent table. you have to change the model code.
class ServiceItem extends Model
{
use HasFactory;
public $fillable = ['service_id', 'item_id', 'values'];
public function service()
{
return $this->belongsTo(Service::class, 'service_id');
}
public function item()
{
return $this->belongsTo(Item::class, 'item_id');
}
}
and then $serviceItem->item should work as expected.

Favorite functionality for my laravel application

I'm currently trying to make a favorite functionality to my laravel application. I'm trying to access the post table with eloquent, but it says property posts(the function in the favorite model) does not exist.
Update: I updated the query. If I dump $favorite I get two items, which is correct, but now I get this error message instead:Property [posts] does not exist on the Eloquent builder instance. (View: C:\xampp\laravelprojects\Skakahand\resources\views\profile\index.blade.php)
<div class="favorite-section">
<p>Mina favoriter</p>
{{$favorite->posts->title}}
</div>
This is my controller:
public function index(User $user)
{
$favorite = Favorite::where('user_id', auth()->user()->id)
->get();
return view('profile.index',[
'user' => $user,
'favorite' => $favorite
]);
}
Favorite model:
class Favorite extends Model
{
use HasFactory;
protected $fillable = [
'user_id'
];
public function users()
{
return $this->belongsTo(User::class);
}
public function posts()
{
return $this->belongsTo(Post::class);
}
}
and post model:
class Post extends Model
{
use HasFactory;
/* use Sluggable; */
protected $fillable = [
'title',
'body',
'category',
'decision',
'number',
'place',
'image_path',
'slug',
'price',
'user_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function favorites(){
return $this->hasMany(Favorite::class);
}
}
First correct Model like this
class Favorite extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'post_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
}
In controller change code like this for for avoid lazy loads
public function index(User $user)
{
$favorites = Favorite::where('user_id', auth()->user()->id)
->with('post')
->get();
return view('profile.index',[
'user' => $user,
'favorites' => $favorites
]);
}
in blade use code like
<div class="favorite-section">
<p>Mina favoriter</p>
<ul>
#foreach($favorites as $favorite)
<li>{{ $favorite->post->title ?? '' }} </li>
#endforeach
</ul>
</div>
just include ->with() for relationship,
your query should look like this
$favorite = Favorite::where('user_id', auth()->user()->id)->with('post')
->get();
return view('profile.index',compact('favorite','user'));

How can I get video of specific model?

I want to display videos for each model in my table, where to define they are connected by their ids?
In my controller:
public function index()
{
$model_video = NewModelVideos::all();
return view('admin.model_new_videos.index')
->with('models', $models)
->with('model_video', $model_video);
}
in my Model:
class NewModelVideos extends Model
{
public function model()
{
return $this->belongsTo('App\Models\NewModels\NewModel', 'model_id');
}
}
class NewModel extends Model
{
public function videos()
{
return $this->hasMany('App\Models\NewModels\NewModelVideos', 'model_id', 'id');
}
}
and View:
#foreach($model_video as $model)
{{ $model->video }}
#endforeach
You should update your code like this:
public function index()
{
$model_video = NewModelVideos::all();
$models = NewModel::all();
return view('admin.model_new_videos.index')
->with('models', $models)
->with('model_video', $model_video);
}
and blade:
#foreach($models as $model)
{{ $model->videos }} //get videos
#endforeach
#foreach($model_video as $video)
{{ $video->model }} //get model
#endforeach

laravel Notification Undefined index: user_id

I going to do massage notification, I already make the notifications steps,
but gives me this error
when I do dd($notifiable); I found all data
Undefined index: user_id OR
Undefined index: name
public function store(Request $request)
{
$chating=new chats();
$chating->chat = $request->input('chat');
$chating->user_id = Auth::id();
$chating->employee_id = $request->input('employeeid');
$chating->save();
$user_id=$request->input('employeeid');
auth()->user()->notify(new SendMassages($user_id));
return redirect()->back();
}
database notifications table coulmn data {"user_id":5,"name":"Ibrahim"}
Model
protected $user_id;
protected $name;
public function __construct($user_id)
{
$this->user_id = $user_id;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'user_id' => $this->user_id,
'user'=>$notifiable
];
}
View:
{{ $notification->data['name'] }}
Model:
class SendMassages extends Notification
{
use Queueable;
public $user;
public $user_id;
public function __construct($user_id)
{
$this->user_id = $user_id;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
// dd($notifiable);
return [
'user_id' => $this->user_id,
'user'=>$notifiable
];
}
}
It seems that you have problem with encapsulation in your code. First you have to make the property of your model into public if you want the quick and not-safe way but if you want the OOP way, You must write setters to do that logic for you.
First and not-safe approach :
class YourModel {
public $user_id;
.
.
.
}
The OOP way:
Class {
public function setUserId(int $userId)
{
$this->user_id = $userId;
}
.
.
.
}
if you are willing to get the exact answer please copy your controllerclass and model in here.

How do I see published posts count with Eloquent using a ServiceProvider

I have a Blog Categories in the sidebar.blade.php
#foreach ($categories as $category)
<li>
<i class="fa fa-angle- right"></i> {{$category->title}}
<span class="badge pull-right">{{$category->posts()->count()}}</span>
</li>
#endforeach
But this count give me all the posts in my database, even the ones that are scheduled to post at a later date.
PostsController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Category;
class PostsController extends Controller
{
protected $limit = 3;
public function index()
{
$posts = Post::with('author')
->latestFirst()
->published()
->paginate($this->limit);
return view('posts.index', compact('posts'));
}
public function category(Category $category)
{
$categoryName = $category->title;
$posts = $category->posts()
->with('author')
->latestFirst()
->published()
->paginate($this->limit);
return view('posts.index', compact('posts', 'categoryName'));
}
Here's the Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use GrahamCampbell\Markdown\Facades\Markdown;
class Post extends Model
{
//Table Name
protected $table = 'posts';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
/*protected $fillable = [
'title',
'excerpt',
'body',
'categery_id',
'image',
];*/
protected $dates = ['published_at'];
public function author()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function getImageUrlAttribute($value)
{
$imageUrl = "";
if( ! is_null($this->image))
{
$imagePath = public_path() . "/img/" . $this->image;
if(file_exists($imagePath)) $imageUrl = asset("img/" . $this->image);
}
return $imageUrl;
}
public function getDateAttribute()
{
return is_null($this->published_at) ? '' : $this->published_at->diffForHumans();
}
public function getExcerptHtmlAttribute(){
return $this->excerpt ? Markdown::convertToHtml(e($this->excerpt)) : NULL;
}
public function getBodyHtmlAttribute()
{
return $this->body ? Markdown::convertToHtml(e($this->body)) : NULL;
}
public function scopeLatestFirst($query)
{
return $query->orderBy('published_at', 'desc');
}
public function scopePublished($query)
{
return $query->where('published_at', '<=', Carbon::now());
}
}
Here's my Category.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
/*protected $fillable = [
'title',
'excerpt',
'body',
'categery_id',
'image',
'slug'
];*/
public function posts()
{
return $this->hasMany(Post::class);
}
public function getRouteKeyName()
{
return 'slug';
}
}
Web.php
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/category/{category}', [
'uses' => 'PostsController#category',
'as' => 'category'
]);
Route::resource('books', 'BooksController');
Route::resource('posts', 'PostsController');
Route::resource('categories', 'CategoriesController', ['except'=> ['create']]);
ComposerServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Category;
use App\Post;
class ComposerServiceProvider extends ServiceProvider
{
public function boot()
{
view()->composer('layouts.sidebar', function($view){
$categories = Category::with(['posts' => function($query){
$query->published();
}])->orderBy('title', 'asc')->get();
return $view->with('categories', $categories);
});
}
}
To recap on what I need done...
I want to just have my published post to be accounted for in the counter to show, not all the of the posts in my database..
(<span class="badge pull-right">{{$category->posts->count()}}</span>)
Post.php
public function scopePublished($query)
{
return $query->where('published_at', '<=', Carbon::now());
}
But this is not working right for me, does anyone know why?
Try this one:
<span class="badge pull-right">{{$category->posts()->published()->count()}}</span>
Didn't try but this should do the trick.

Resources