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)
Related
I want to get Instagram profile total followers and following and post get this error" 429 Too Many Requests on Laravel.
I need for it to show my users profile information on their account page on my website. I tried it, but I didn't get the profile json data.
Here I send my route view and controller.
1. routes/web.php
Route::get('instagram', 'InstagramController#index');
2. app/Http/Controllers/InstagramController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class InstagramController extends Controller {
/**
* Get the index name for the model.
*
* #return string
*/
public function index(Request $request) {
$items = [];
if($request->has('username')){
$client = new \GuzzleHttp\Client;
$url = sprintf('https://www.instagram.com/%s/media', $request->input('username'));
$response = $client->get($url);
$items = json_decode((string) $response->getBody(), true)['items'];
}
return view('instagram',compact('items'));
}
}
3. resources/views/instagram.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5 Instagram API tutorial with example</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h2>Laravel 5 Instagram API tutorial with example</h2><br/>
<form method="GET" role="form">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" id="username" name="username" class="form-control" placeholder="Enter Instagram Username" value="{{ old('username') }}">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<button class="btn btn-success">Search</button>
</div>
</div>
</div>
</form>
<div class="panel panel-primary">
<div class="panel-heading">Instagram Feed</div>
<div class="panel-body">
<table class="table table-bordered">
<thead>
<th>No</th>
<th width="200px;">Id</th>
<th>Code</th>
<th>Image</th>
<th>Location</th>
<th>Total Likes</th>
<th>Total Comments</th>
</thead>
<tbody>
#if(!empty($items))
#foreach($items as $key => $item)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $item['id'] }}</td>
<td>{{ $item['code'] }}</td>
<td><img src="{{ $item['images']['standard_resolution']['url'] }}" style="width:100px;"></td>
<td>{{ isset($item['location']['name']) ? $item['location']['name'] : '' }}</td>
<td>{{ $item['likes']['count'] }}</td>
<td>{{ $item['comments']['count'] }}</td>
</tr>
#endforeach
#else
<tr>
<td colspan="4">There are no data.</td>
</tr>
#endif
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
#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'));
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
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
]);
I have written this code
app\Http\Controller\processController.php
class ProcessController extends BaseController {
public function getData()
{
$data['data']=DB::table('process_table')->get();
if(count($data) > 0)
{
return view('process',$data);
}
else
{
return view('process');
}
} }
route\web.php
Route::get('/process', 'processController#getData');
resources\views\process.blade.php
What should i write here in blade file and how to print $data values in table format ??
The key values of your array are the names of the variables you can use in your view. So, in your case $data will contain all rows from the table process_table.
To make sure that the variable exists, you can use the isset function.
Now you can do this for example:
#if (isset($data))
<ul>
#foreach ($data as $row)
<li>{{ $row->name }}</li>
#endforeach
</ul>
#endif
you can simply dump it
#if (isset($data))
{{{ json_encode($data) }}}
#endif
You should try this:
app\Http\Controller\processController.php
class ProcessController extends BaseController {
public function getData()
{
$data['data']=DB::table('process_table')->get();
if(count($data) > 0)
{
return view('process',compact('data'));
}
else
{
return view('process');
}
}
}
resources\views\process.blade.php
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 style="color: purple;"><center><b>Process Data</b></center></h1>
<hr>
#if(isset($data))
<div class="tab-content">
<div role="tabpanel" class="tab-pane tab-margin table-area-margin active" id="profile">
<div class="table-responsive">
<table class="table payment-info-tbl">
<tr class="displaying-passages-title">
<th>Your Field</th>
</tr>
#foreach ($data as $datas)
<tr>
<td>{{$datas->yourField}}</td>
</tr>
#endforeach
</table>
</div>
</div><!--tab panel profile-->
</div><!--tab content-->
#else
<h1>No Data</h1>
#endif
</div>
</div>
you lookin for this:
#if (isset($data))
<table>
#foreach ($data as $key => $row)
<tr>
<td>{{ $key }}</td>
<td>{{ (is_array($row)) ? json_encode($row) : $row }}</td>
</tr>
#endforeach
</table>
#endif