Invite methods does not exist - laravel

I need all the invitations in show. This I want to do under a company when that company is selected must invite come forth only now I get the error.
Method invite does not exist (Im very new in Vue.js)
Overview.vue code
<v-container fluid grid-list-md>
v-layout v-if="query === 'invites'" align-space-between justify-center row fill-height wrap>
<span v-for="invite in invites" :key="invite.id">{{ invite.email }}</span>
</v-layout>
InviteController index:
public function index( Manager $fractal, InviteTransformer $inviteTransformer ) {
Auth::user()->authorizeRoles( 'user.view' );
// Get all companies
$companies = Auth::user()->companies()->get();
$invites = $companies->invites()->get();
// Restructure for output
$collection = new Collection( $invites, $inviteTransformer );
$data = $fractal->createData( $collection )->toArray();
return $this->respond( $data );
}
ComapnyModel:
<?php
namespace App\Models\Manage;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
// This table does not have timestamps
public $timestamps = false;
protected $fillable = [ 'name' ];
public function users() {
return $this->hasMany( 'App\Models\Manage\User' )->orderBy('lastname')->orderBy('firstname')->orderBy('id');
}
public function userIds() {
return $this->users()->pluck('id');
}
public function admins() {
return $this->belongsToMany( 'App\Models\Manage\User' )->orderBy('lastname')->orderBy('firstname')->orderBy('id');
}
public function adminIds() {
return $this->admins()->pluck('id');
}
public function invites() {
return $this->hasMany( 'App\Models\Manage\Invite' )->orderBy('email')->orderBy('id');
}
}

Ficed by myself i needed to remove ->get();

Related

laravel get parent data from child relationship

Hi i have this relationship between Customers and Claims
Customers Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customers extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'contr_nom',
'contr_cog',
'benef_nom',
'benef_cog',
'email',
'polizza',
'targa',
'iban',
'int_iban',
'cliente',
];
public function claims()
{
return $this->hasMany(Claims::class);
}
public function refunds()
{
return $this->hasManyThrough(Refunds::class, Claims::class);
}
}
Claims model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Claims extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'dossier',
'date_cla',
];
public function refunds()
{
return $this->hasMany(Refunds::class);
}
public function customers()
{
return $this->belongsTo(Customers::class,'customers_id');
}
}
I need to put some information from claims and from customers in a datatable
They have a parent-child relationship as first and second columns of datatables i put id and dossier from Claims table, but how i can get for example contr_nom, contr_cog, email, polizza, etc. from Customer table for each dossier?
I tried with this controller
class ComptaController extends Controller
{
public function index(Request $request){
if ($request->ajax()) {
$data = Claims::with('customers')->get();
/*Cannot access to Customers from $data but i can see in the relationship*/
dd($data->customers->contr_nom); GIVE ME ERROR
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'Edit Delete';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('pages.compta');
}
}
but i cannot access to customers data for each dossier..
Thx.
foreach($data->customers as $customer){
dd($customer->contr_nom);
}
or
Claims::with(array('customer'=>function($query){
$query->select('id','contr_nom');
}))->get();
Using datatables I guess you can add related customer details by adding columns with a closure method like
return Datatables::of($data)
->addIndexColumn()
->addColumn('contr_nom',function($row){
return $row->customers->contr_nom;
})
->addColumn('contr_cog',function($row){
return $row->customers->contr_cog;
})
->addColumn('email',function($row){
return $row->customers->email;
})
//.. and so on otehr columns
->addColumn('action', function($row){
$btn = 'Edit Delete';
return $btn;
})
->rawColumns(['action'])
->make(true);
I guess you have one customer per claim so its better if you rename customers() to customer() in claim model it makes more sense

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.

Laravel 5.5 Relationships

I'm trying to implement relationships between models and i recieve "Trying to get property 'products' of non-object" and i don't understand why, because i used this before in the same way and it's worked fine.
The logic of relationship is that 1 Merchant hasMany Products
this is the code that i'm using:
Merchant Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Merchant extends Model {
protected $table = "merchants";
protected $fillable = [
'merchant_id', 'merchant_name', 'secret_key', 'merchant_address', 'merchant_phone', 'merchant_admin',
'merchant_contact', 'merchant_mail', 'merchant_description', 'enable', 'created_at', 'updated_at'];
public function users() {
//many to many
return $this->belongsToMany('App\User');
}
public function branchOffices() {
return $this->hasMany('App\BranchOffice', 'merchant_id', 'merchant_id');
}
public function products() {
return $this->hasMany('App\Products', 'merchant_id', 'merchant_id');
}
public function transactions() {
return $this->hasMany('App\Transaction', 'merchant_id', 'merchant_id');
}
public function readers() {
return $this->hasMany('App\Reader', 'merchant_id', 'merchant_id');
}
}
Product Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
protected $table = "products";
protected $fillable = [
'id', 'barcode', 'description', 'price', 'currency_id', 'merchant_id', 'branch_id',
'enable', 'created_at', 'updated_at'];
public function merchants() {
return $this->belongsTo('App\Merchant', 'merchant_id', 'merchant_id');
}
public function currencies() {
return $this->belongsTo('App\Currency', 'iso_4712', 'currency_id');
}
public function branch_sectors() {
return $this->belongsToMany('App\BranchSector');
}
}
And this is the method in ProductController:
public function merchantProducts() {
$products = Merchant::find('merchant_id')->products;
return $products;
}
If someone can help me i'll be very thankfull.
Thanks in advance!!
Assume merchant is not guaranteed existing in database giving merchant id, it is better off to check if merchant exists, and retrieves its products if so.
$products = collect();
$merchant = Merchant::find($merchant_id);
if($merchant) {
$products = $merchant->products;
}
return $products;
all!!
Finally i solved this problem using resources in this way:
public function merchantProducts(Request $request) {
$merchant_id = $request->merchant_id;
$products = Product::where('merchant_id', $merchant_id)->paginate(15);
return ProductResource::collection($products);
}
Thanks to all!!

Laravel Method sync does not exist

Post Model
<?php
namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function tags(){
return $this->belongsToMany('App\Model\User\Tag','post__tags', 'post_id', 'tag_id');
}
public function categories() {
return $this->belongsToMany('App\Model\User\Category','category__posts','post_id', 'category_id');
}
}
Category Model
<?php
namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts(){
return $this->belongsToMany('App\Model\User\Category','category__posts', 'post_id', 'category_id');
}
}
Tag Model
<?php
namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
public function posts() {
return $this->belongsToMany('App\Model\User\Post','post__tags','post_id','tag_id');
}
}
PostController.php
public funcion store()
{
// do validation here
try{
$post = new Post;
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->slug = $request->slug;
$post->body = $request->body;
$post->status = 1;
$post->save(); // This works correct
$post->tags->sync($request->tags); // Not working
$post->categories->sync($request->categories); // Not working
}
catch(\Exception $e){
return redirect(route('post.index'))->with('message', 'Error Adding Post into system!'.$e->getMessage()); // getting Message "Method sync does not exist. "
}
}
Sync is a method on the builder instance, you're using it on the collection.
// change your code like this
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
You need to use the following:
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
Don't forget the () in tags and categories
$post->categories without () is a Collection instance.
$post->categories() is a belongsToMany instance

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

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

Resources