Laravel Problem Call to undefined method App\Models\User::getRoleNames() - laravel

#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Users Management</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('users.create') }}"> Create New User</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Email</th>
<th>Roles</th>
<th width="280px">Action</th>
</tr>
#foreach ($data as $key => $user)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
#if(!empty($user->getRoleNames()))
#foreach($user->getRoleNames() as $v)
<label class="badge badge-success">{{ $v }}</label>
#endforeach
#endif
</td>
<td>
<a class="btn btn-info" href="{{ route('users.show',$user->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('users.edit',$user->id) }}">Edit</a>
{!! Form::open(['method' => 'DELETE','route' => ['users.destroy', $user->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
</table>
{!! $data->render() !!}
<p class="text-center text-primary"><small>Tutorial by ItSolutionStuff.com</small></p>
#endsection

Im agree with Gary, if you are using Spatie add the next code to User.php
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;

Please add this method into User.php model file
public function getRoleNames()
{
return $this->belongsToMany(Role::class);
}
If this method not work then share you table structure and user model file code.

In the controller that call this view, you should to do:
$data = Model::all(); // ---> this solved that for me
return view('model.view',compact('data'));

Related

How to get data from a related table in laravel

I am trying to get data of an animal through a relationship with the user table
Here is my controller
<?php
namespace App\Http\Controllers;
use App\Animal;
use App\Clinic;
use App\Role;
use App\Slaughter;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ClinicController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$farms = User::where('role_id', 3)->get();
$user = Auth::user();
$animal = Animal::all();
return view('clinic.index', compact('user', 'animal', 'farms'));
}
public function show($id)
{
$farm = User::query()->findOrFail($id);
return view('clinic.show', compact('farm'));
}
While getting the user which is Farm in my case, I would like to get the animals the farm admin registered through this relationship
Model
class Clinic extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}
}
From My tinker, the relationship is working perfectly
Here comes my index page
#extends('layouts.app')
#section('content')
<br><br><br><br><br><br>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-20">
<div class="card">
<div class="card-header">
<center>
<h1>Clinic Dashboard</h1>
</center>
</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<center>
<h2>Welcome! <strong>{{ Auth::user()->name }}</strong></h2>
</center>
<hr>
<br>
<div class="container box">
<div class="table-responsive">
<table class="table table-striped table-bordered" style="background: white">
<thead>
<tr>
<th>Farm Id</th>
<th>Farm Name</th>
<th>Action</th>
</tr>
</thead>
#foreach( $farms as $farm)
<tbody>
<tr>
<td>{{ $farm->id }}</td>
<td>{{ $farm->name }}</td>
<td><a href="/clinic/{{ $farm->id }}"><button
class="btn btn-outline-primary">View Farm
Animals</button></a></td>
</tr>
</tbody>
#endforeach
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
And my route
Route::get('/clinic/{farm}', 'ClinicController#show');
And finally the show view where I am getting all the errors
#extends('layouts.app')
#section('content')
<br><br><br><br><br><br>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-20">
<div class="card">
<div class="card-header">
<center>
<h1>Farm Dashboard</h1>
</center>
</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<center>
<h2>Welcome! <strong>{{ Auth::user()->name }}</strong></h2>
</center>
<hr>
<br>
<div class="container box">
<div class="table-responsive">
<table class="table table-striped table-bordered" style="background: white">
<thead>
<tr>
<th>Id</th>
<th>Animal Type</th>
<th>Sex</th>
<th>Farm</th>
<th>Clinic</th>
<th>Vaccination</th>
<th>Nutrition</th>
</tr>
</thead>
#foreach( $farm as $farm)
<tbody>
<tr>
<td>{{ $farm->animals->id }}</td>
<td>{{ $farm->animals->type->category }}</td>
<td>{{ $farm->animals->gender }}</td>
<td>{{ $farm->animals->user->name }}</td>
#if(! $farm->animals->clinic)
<td>N/A</td>
<td>N/A</td>
<td>N/A</td>
<td>
<a href="/clinic/{{ $farm->animals->id }}/create">
<button type="button" class="btn btn-primary">
Attach Clinic Detail
</button>
</a>
</td>
#elseif( $farm->animals->clinic)
<td>{{ $farm->animals->clinic->user->name }}</td>
<td>{{ $farm->animals->clinic->vaccination ?? 'N/A' }}</td>
<td>{{ $farm->animals->clinic->nutrition ?? 'N/A'}}</td>
<td>
<a
href="/clinic/{{ $farm->animals->clinic->id }}/edit">
<button type="button"
class="btn btn-primary">Edit Animal
Clinic details</button>
</a>
</td>
#endif
</tr>
</tbody>
#endforeach
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
I hope I have provided all the fields that could be generating errors. Any assist will be kindly taken as it is a very important project for me
The error I am getting is
Trying to get property 'animals' of non-object
this setup allows you to get all the animals of all the users of a specific clinic. I leveraged route/model binding on your show() method too. Whatever ID you pass in the URL it will automatically load the clinic up.
// app/User.php
class User extends Autheticatable
{
public function animals()
{
return $this->hasMany('App\Animal');
}
public function clinic()
{
return $this->belongsTo('App\Clinic');
}
}
// app/Clinic.php
class Clinic extends Model
{
public function users()
{
return $this->hasMany('App\User');
}
}
// app/Animal.php
class Animal extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
class ClinicController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function show(Clinic $clinic)
{
return view('clinic.show', compact('clinic'));
}
}
// view
#foreach($clinic->users as $farm)
#foreach($farm->animals as $animal)
{{ $animal->name }} - {{ $animal->weight }} etc...
#endforeach
#endforeach
In your view you have #foreach($farm as $farm)
What you need: #foreach($farms as $farm)
Edit: this only addresses part of the issue, upon closer inspection your relationships are out of whack, I'll see if I can whip something up.
To get the related Animals for the $farm I would go
public function show($id)
{
$farm = User::with(['animals'])->findOrFail($id);
return view('clinic.show', compact('farm'));
}
Then in your blade
#foreach($farm->animals as $animal)
{{ $animal->id }}
#endforeach
This is assuming you have your animal relation set in your user model of course which would be something like
public function animals()
{
return $this->hasMany('App\Animals')
}
(All untested)

Laravel 5 : Undefined variable: post

in my view, I got an error, Undefined variable: post (View: /Applications/MAMP/htdocs/night-copy/resources/views/posts/index.blade.php).
I don't know why it happens. Please help me out.
I am creating a CRUD dashboard for admin side.
I will paste some of my codes, so if you need more codes, please ask me.
PostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\Posts\CreatePostsRequest;
use App\Http\Requests\Posts\UpdatePostRequest;
use App\Post;
class PostsController extends Controller
{
public function index()
{
return view('posts.index')->with('posts', Post::all());
}
public function create()
{
return view('posts.create');
}
public function store(CreatePostsRequest $request)
{
//upload the image to strage
//dd($request->image->store('posts'));
$image = $request->image->store('posts');
//create the posts
Post::create([
'image' => $image,
'title' => $request->title,
'place' => $request->place,
'map' => $request->map,
'date' => $request->date,
'tag' => $request->tag,
'description' => $request->description
]);
//flash message
session()->flash('success', 'Post created successfully.');
//resirect user
return redirect(route('posts.index'));
}
public function show($id)
{
//
}
public function edit(Post $post)
{
return view('posts.create')->with('post', $post);
}
public function update(UpdatePostRequest $request, Post $post)
{
$data = $request->only(['title', 'place', 'map', 'date', 'published_at', 'tag', 'description']);
//check if new image
if($request->hasFile('image')){
//upload it
$image = $request->image->store('posts');
//delete old image
$post->deleteImage();
$data['image'] = $image;
}
//update attributes
$post->update($data);
//flash message
session()->flash('success', 'Post updated sucessfully.');
//redirect user
return redirect(route('posts.index'));
}
public function destroy($id)
{
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
if($post->trashed()) {
$post->deleteImage();
$post->forceDelete();
} else {
$post->delete();
}
session()->flash('success', 'Post deleted successfully.');
return redirect(route('posts.index'));
}
public function trashed()
{
$trashed = Post::onlyTrashed()->get();
return view('posts.index')->with('posts', $trashed);
}
public function restore($id)
{
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
$post->restore();
session()->flash('success', 'Post restore successfully.');
return redirect()->back();
}
}
index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
<link rel="stylesheet" href="{{ asset('/css/main-posts.css') }}">
<title>Event Confirmation</title>
</head>
<body>
<div class="container">
<div class="header">
<h2 class="logo">Dark Code</h2>
<input type="checkbox" id="chk">
<label for="chk" class="show-menu-btn">
<i class="fas fa-bars" style="color: white;"></i>
</label>
<ul class="menu">
<div class="menu-list">
<i class="fa fa-home" ></i>
Dashboard
Post
Category
Suspended
Logout
<label for="chk" class="hide-menu-btn">
<i class="fas fa-times" style="color: white;"></i>
</label>
</div>
</ul>
</div>
<div class="content">
<div class="userinfo">
<div class="content">
#if($posts->count() > 0)
<table class="table">
<thead>
<th>ID</th>
<th>Title</th>
<th>Location</th>
<th>Map</th>
<th>Date</th>
<th>Tags</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr></tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->place }}</td>
<td>{{ $post->map }}</td>
<td>{{ $post->date }}</td>
<td>{{ $post->tag }}</td>
#if($post->trashed())
<form action="{{ route('restore-posts', $post->id) }}" method="POST">
#csrf
#method('PUT')
<button class="save-btn" type="submit">Restore</button>
</form>
<br>
#else
<button btn="" class="edit-btn">
Edit
</button><br>
#endif
</td>
<td>
<form action="{{ route('posts.destroy', $post->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="delete-btn" >
{{ $post->trashed() ? 'Delete' : 'Trash' }}
</button><br>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
#else
<h3 style="margin: 15rem; color: white;">No Posts Yet</h3>
#endif
</div>
</div>
</div>
</div>
#if($post->trashed())
#else
<button btn="" class="add-btn">Add</button>
#endif
<div class="footer">
</div>
</body>
</html>
web.php
Route::resource('posts', 'PostsController');
Route::get('trashed-posts', 'PostsController#trashed')->name('trashed-posts.index');
Route::PUT('restore-post/{post}', 'PostsController#restore')->name('restore-posts');
In your view, you're calling #if($post->trashed()) outside of #endforeach block so the $post is outside the scope by then and hence undefined variable.
Besides the #if statement there is redundant, you want the user to be able to create a new post regardless whether a specific post is trashed or not
<div class="content">
<div class="userinfo">
<div class="content">
#if($posts->count() > 0)
<table class="table">
<thead>
<th>ID</th>
<th>Title</th>
<th>Location</th>
<th>Map</th>
<th>Date</th>
<th>Tags</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr></tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->place }}</td>
<td>{{ $post->map }}</td>
<td>{{ $post->date }}</td>
<td>{{ $post->tag }}</td>
#if($post->trashed())
<form action="{{ route('restore-posts', $post->id) }}" method="POST">
#csrf
#method('PUT')
<button class="save-btn" type="submit">Restore</button>
</form>
<br>
#else
<button btn="" class="edit-btn">
Edit
</button><br>
#endif
</td>
<td>
<form action="{{ route('posts.destroy', $post->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="delete-btn">
{{ $post->trashed() ? 'Delete' : 'Trash' }}
</button><br>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
#else
<h3 style="margin: 15rem; color: white;">No Posts Yet</h3>
#endif
</div>
</div>
</div>
</div>
<button btn="" class="add-btn">Add</button>
In your view file Check this line #if($post->trashed()). this is outside of foreach loop. comment this line out or remove it

Error "Trying to get property 'pertanyaan' of non-object" on Dompdf Laravel 5.8

I have a view and I want to have a link that downloads a PDF.
View
<div class="col-lg-12 col-xs-12">
<div class="box">
Download PDF
<div class="box-header">
<div style="text-align:center"><h3 class="box-title">PEMELIHARAAN DAN PERAWATAN ALAT UJI </h3></div>
<div style="text-align:center">Jln. Kabupaten Sragen</div>
</div>
<p> Laporan : {{ $pemeliharaan->status }} </p>
<p> Tanggal : {{ $pemeliharaan->created_at }} </p>
<p> Jenis Alat : {{ $pemeliharaan->alat->nama_alat }} </p>
<p> User : {{ $pemeliharaan->user->name }} </p>
<div class="box">
<div class="box-header">
<h3 class="box-title"></h3>
</div>
<div class="box-body no-padding">
<table class="table table-condensed">
<tbody>
<tr>
<th style="width: 10px">#</th>
<th>Pertanyaan</th>
<th>Hasil</th>
</tr>
<tr>
<td>1.</td>
<td>{{ $pemeliharaan->pertanyaan['question1'] }}</td>
<td>{{ $pemeliharaan->pertanyaan['answer1'] }}</td>
</tr>
<tr>
<td>2.</td>
<td>{{ $pemeliharaan->pertanyaan['question2'] }}</td>
<td>{{ $pemeliharaan->pertanyaan['answer2'] }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
The link 'download' has an error.
Just Showing 404
Controller
public function showQuestion(Request $request, $id)
{
$pemeliharaan = Pemeliharaan::findOrFail($id);
$pemeliharaan->pertanyaan = json_decode($pemeliharaan->pertanyaan, true);
if ($request->has('download')) {
$pdf = PDF::loadView('users.view_question', $pemeliharaan);
return $pdf->download('view_question.pdf');
}
return view('users.view_question', compact('pemeliharaan'));
}
Routes
Route::get('/user/show/question/pdf/{id}','userController#showQuestion')->name('pdf');
Route::get('user/show/question/{id}', 'userController#showQuestion')->name('usershowQuestion');
Can someone help me with the code for the download?
You are not supplying the id route parameter to the named route 'pdf'. That's causing the line $pemeliharaan = Pemeliharaan::find($id) to yield null and later an error.
Try this:
{{ route('pdf', [ $id ] }}
In order for it to work you must supply the variable $id to the view. You can do that something like
return view('your-view')->with([
"id" => $id
]);

Display date to view with a M-D-Year

I am new to laravel, with regards to displaying the date to the view with the MM-DD-YYYY format
#extends('layouts.common')
#section('title' ,'Administrator | Category')
#section('contents')
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">All Categories</div>
<div class="panel-body">
<table class="table">
<thead class="thead-inverse">
<tr>
<th>Category Name</th>
<th>Published At</th>
</tr>
</thead>
<tbody>
#foreach($categories as $category)
<tr>
<td><a href="{{ url('/category', $category->id) }}"> {{
$category->name }}</a></td>
<td>{{$category->published_at }}</td>
<td><a href="{{ route('category.edit',$category->id) }}"><i
class="icon fa fa-edit"></i>&nbsp&nbsp&nbsp</a><i
class="icon fa fa-times"></i></td>
</tr>
</tbody>
#endforeach
</table>
</div>
</div>
</div>
</div>
#endsection #section('js') {!!Html::script('assets/js/jquery.min.js')!!}
{!!Html::script('assets/js/bootstrap.min.js') !!} #endsection
With regards to that i would like to display to the view the {{$category->published_at }} data into that format. Please help thanks
Please follow way below
{!! date('d-m-Y', strtotime($model->start_date)) !!}
or
{{ date('d-m-Y', strtotime($model->start_date)) }}
I Hope Help You!
In your Category model
public $dates = ['published_at'];
Then in view you can use
$category->published_at->format('m-d-Y')
Further reading: Eloquent: Mutators
Another approach. Extends Skysplit answer
In Category Model
public function getPublishedAtAttribute(){
return $this->attributes['published_at']->format('m-d-Y');
}
And never worry about published_at again. Just
$category->published_at

Nested html formBuilder with Laravel

cart.blade.php
#extends('master')
#section('content')
<div class="container">
#if(Cart::isEmpty())
<b>The card is empty</b> Shopping now
#else
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th>item id</th>
....
</tr>
</thead>
<tbody>
{!! Form::open(["url"=>"/pay"]) !!}
<?php $i = 0; $totalCart_price = 0; ?>
#foreach($cart_total_items as $item)
<tr>
<td>{{ $item['id'] }}</td>
....
<td>
{!! Form::open(["url"=>"/my-cart/".$item['id'], "method"=>"DELETE", "style"=>"display: inline"]) !!}
<button type="submit" class="btn btn-danger" aria-label="Left Align">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
{!! Form::close() !!}
</td>
</tr>
<?php $i++; $totalCart_price += Cart::get($item['id'])->getPriceSum(); ?>
#endforeach
</tbody>
</table>
<b>Total price: ${{ $totalCart_price }} {{ Form::hidden("total_price", $totalCart_price) }}</b>
<br><br>
{!! Form::submit('check out (paypal)', ["class"=>"btn btn-primary"]) !!}
{!! Form::close() !!}
Clear cart
#endif
</div>
#stop
Issue: I can delete any item, but during click check out nothing happens, but when I remove clear item form, check out run successfully.
I want to run two operations, How Can I solve it?
Thanks
You can have several forms in a page but they should not be nested.
As given in html5 working draft:
4.10.3 The form element
Content model:
Flow content, but with no form element descendants.
As far as I know form is just the html tags which can be used to send a group(array) of data at once to the server.
In your case your best bet would be to use the ajax query.(though it would make our page javascript dependent)
Or, as I observed you can just seperate the two form like below:
#extends('master')
#section('content')
<div class="container">
#if(Cart::isEmpty())
<b>The card is empty</b> Shopping now
#else
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th>item id</th>
....
</tr>
</thead>
<tbody>
<<!-- Remove the Form tag from here and insert it below -->>
<?php $i = 0; $totalCart_price = 0; ?>
#foreach($cart_total_items as $item)
<tr>
<td>{{ $item['id'] }}</td>
....
<td>
{!! Form::open(["url"=>"/my-cart/".$item['id'], "method"=>"DELETE", "style"=>"display: inline"]) !!}
<button type="submit" class="btn btn-danger" aria-label="Left Align">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
{!! Form::close() !!}
</td>
</tr>
<?php $i++; $totalCart_price += Cart::get($item['id'])->getPriceSum(); ?>
#endforeach
</tbody>
</table>
<<!-- Remove the Form tag from above and insert it below -->>
{!! Form::open(["url"=>"/pay"]) !!}
<b>Total price: ${{ $totalCart_price }} {{ Form::hidden("total_price", $totalCart_price) }}</b>
<br><br>
{!! Form::submit('check out (paypal)', ["class"=>"btn btn-primary"]) !!}
{!! Form::close() !!}
Clear cart
#endif
</div>
#stop

Resources