Here, I retrieve two tables to be displayed on one view page. The images are in the users table. When I clicked the profile tab, it displayed an error message:
Trying to get property of non-object.
What is wrong with my codes referring to the error message?
upload.blade.php
<div id="templatemo_sidebar">
<tr>
<div id="login">logged in as :</div>
</tr>
#foreach($users as $users)
<div id="img">
<img src="{!! '/profiles/'.$users->filePath !!}">{{$users->filePath}}
</div>
#endforeach
{!! Form::open(['action'=>'ProfileController#store', 'files'=>true]) !!}
<div class="form-group">
{!! Form::label('image', 'Choose an image') !!}
{!! Form::file('image') !!}
</div>
<div class="form-group">
{!! Form::submit('Save', array( 'class'=>'btn btn-danger form-control' )) !!}
</div>
{!! Form::close() !!}
#foreach($profiles as $profile)
<div id="profile_sidebar">
<tr>
<td>{{$profile->student_name}}</td>
</tr>
<tr>
<td>{{$profile->student_id}}</td>
</tr><br>
<tr>
<td>{{$profile->student_ic}}</td>
</tr>
<tr><br>
<td><mark>Status : {{$profile->status}}</mark></td>
</tr>
#endforeach
</div>
ProfileController.php
public function store(Request $request)
{
$users = Auth::user();
if($request->hasFile('image')) {
$file = Input::file('image');
//getting timestamp
//$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
//$name = $timestamp. '-' .$file->getClientOriginalName();
$name=$file->getClientOriginalName();
$users->filePath = $name;
$file->move(public_path().'/profiles/', $name);
}
$users->save();
$users = Auth::user();
$users = Profile::where('student_id', $users->student_id)->get();
$profiles = Profile::all();
return view('profile', compact('users', 'profiles'));
}
}
Profile.php
class Profile extends Model
{
protected $table='profiles';
protected $fillable = ['student_id','student_name', 'program','faculty'];
public function user()
{
return $this->belongsTo('users');
}
public function setFirstNameAttribute($value) {
$this->attributes['faculty'] = ucfirst($value);
}
public function setLastNameAttribute($value) {
$this->attributes['program'] = ucfirst($value);
}
public function profilePicture(){
return $this->belongsTo('User', 'student_id');
}
}
In your first foreach you have to use a different variable for iterating through the users collection, like this:
#foreach($users as $user)
Related
I am running Laravel 7 and have a list of tasks (would be posts if it were a blog) and I need to make sure that when the task is deleted, that all subsequent images are deleted in both the database and in the disc. When I click the delete button, the page throws an error: Invalid argument supplied for foreach().
Unfortunately, this is a vague error and can be caused by a variety of causes. My hopes are that someone can take a look at my code and see if I am missing something. I am relatively new to Laravel so tracking down this issue has been more than a challenge. Than you in advance for helping my work out this issue.
In my Task.php model, I have:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Image;
use Illuminate\Support\Facades\Storage;
class Task extends Model
{
protected $fillable = [
'task_name', 'task_priority', 'task_assigned_to', 'task_assigned_by', 'task_description', 'task_to_be_completed_date', 'task_status',
'task_notes'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function image()
{
// return $this->hasMany('App\Image');
return $this->hasMany(Image::class);
}
public static function boot()
{
parent::boot();
self::deleting(function ($task) {
foreach ($task->images as $image) {
$image->delete();
}
});
}
}
In my Image.php model, I have
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use App\Task;
class Image extends Model
{
protected $fillable = [
'task_id',
'name',
];
protected $uploads = '/task-images/';
public function getFileAttribute($image)
{
return $this->uploads . $image;
}
public function task()
{
// return $this->belongsTo('App\Task', 'task_id');
return $this->belongsTo(Task::class);
}
public static function boot()
{
parent::boot();
self::deleting(function ($image) {
Storage::delete(Storage::path($image->name));
});
}
}
In my TasksController.php, (all code in case something is causing a conflict here) here is what I have:
<?php
namespace App\Http\Controllers;
use App\Task;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class TasksController extends Controller
{
public function index()
{
$tasks = Task::orderBy('created_at', 'desc')->paginate(10);
return view('/tasks')->with('tasks', $tasks);
}
public function create()
{
return view('tasks.create');
}
public function store(Request $request)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
// Create Task
$user = Auth::user();
$task = new Task();
$data = $request->all();
$task->user_id = $user->id;
$task = $user->task()->create($data);
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
$images = new Image;
$images->name = $name;
}
}
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->task_status;
$task->save();
return redirect('/home')->with('success', 'Task Created');
}
public function edit($id)
{
$task = Task::find($id);
return view('tasks.edit', ['task' => $task]);
}
public function update(Request $request, $id)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
$task = Task::find($id);
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->input('task_status');
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
}
}
$task->update();
return redirect('/home')->with('success', 'Task Updated');
}
public function show($id)
{
$task = Task::find($id);
return view('tasks.show')->with('task', $task);
}
public function destroy($id)
{
$task = Task::findOrFail($id);
// dd($task);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
}
And in the home page where I am calling the delete function, `home.blade.php`, I have:
#extends('layouts.master')
#section('content')
<div class="custom-container">
<div class="row justify-content-center">
<div class="col-md-12">
#include('layouts.includes.messages')
<div class="card w-100">
<div class="card-header text-white" style="background-color: #605ca8;">
<h3 class="card-title">Tasks</h3>
<div class="card-tools">
<a href="tasks/create" class="btn btn-success">
<i class="fas fa-tasks"></i> Add New Task
</a>
</div>
</div>
<!-- /.card-header -->
</div>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Ongoing Tasks</h3>
<div class="card-tools">
<div class="input-group input-group-sm" style="width: 150px;">
<input type="text" name="table_search" class="form-control float-right" placeholder="Search">
<div class="input-group-append">
<button type="submit" class="btn btn-default"><i class="fas fa-search"></i></button>
</div>
</div>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>Task</th>
<th>Priority</th>
<th>Assigned To</th>
<th>Test Environment Date</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#if($tasks->count() > 0)
#foreach($tasks as $task)
<tr>
<td>{{ $task->task_name }}</td>
<td>{{ $task->task_priority }}</td>
<td>{{ $task->task_assigned_to }}</td>
<td>{{$task->task_to_be_completed_date }}</td>
<td>{{ $task->task_status }}</td>
<td>
<a href="tasks/{{$task->id}}/edit" class="btn btn-primary btn-sm mr-2">
<i class="fa fa-edit"></i> Edit
</a>
<form action="tasks/{{$task->id}}" method="POST" style="display: inline" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</td>
</tr>
#endforeach
#else
<p class="ml-4 pt-2">No Tasks Found. Please Add one.</p>
#endif
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</div>
</div>
{{ $tasks->links() }}
</div>
</div>
#endsection
In my filesystem.php under the config folder, I have(just for storage):
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
// 'root' => public_path('task-images'),
],
If I missed anything or codes, please let me know so I can edit my question. Thank you again in advance for helping me with this issue.
You are trying to access a property named images on your instance of Task but there isn't an attribute named images and there isn't a relationship named images, so null is being returned: $task->images == null. You named your relationship image not images, though images would be more correct since this relationship can return many; plural. Change the name of the relationship to images:
public function images()
{
return $this->hasMany(Image::class);
}
Or reference it by its current name: $task->image
i wanna update the data of categories on multilevel choose item, but i had a problem, i can edit the categories without choose a parent, but i can't edit the categories when i choose a parent. then its showing a error called undefined offset:1 and here the trace error
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError
C:\laragon\www\oesingcoffee\vendor\laravel\framework\src\Illuminate\Validation\Concerns\ValidatesAttributes.php:874
this is validates attrib in laravel framework
protected function getExtraConditions(array $segments)
{
$extra = [];
$count = count($segments);
for ($i = 0; $i < $count; $i += 2) {
$extra[$segments[$i]] = $segments[$i + 1]; //this is the 874 line
}
return $extra;
}
this is the CategoryRequest class
class CategoryRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$parentId = (int) $this->get('parent_id');
$id = (int) $this->get('id');
if($this->method() == 'PUT'){
if($parentId > 0){
$name = 'required|unique:categories,name,'.$id.'id,parent_id,'.$parentId;
}else{
$name = 'required|unique:categories,name,'.$id;
}
$slug = 'unique:categories,slug,'.$id;
}else{
$name = 'required|unique:categories,name,NULL,id,parent_id,'.$parentId;
$slug = 'unique:categories,slug';
}
return [
'name' => $name,
'slug' => $slug,
];
}
}
this is my controller to update the data
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$params['slug'] = Str::slug($params['name']);
$params['parent_id'] = (int)$params['parent_id'];
$category = Category::findOrFail($id);
if ($category->update($params)) {
Session::flash('success', 'Category has been updated.');
}
return redirect('admin/categories');
}
this the view form
#extends('admin.layout')
#section('content')
#php
$formTitle = !empty($category) ? 'Update' : 'New'
#endphp
<div class="content">
<div class="row">
<div class="col-lg-6">
<div class="card card-default">
<div class="card-header card-header-border-bottom">
<h2>{{ $formTitle }} Category</h2>
</div>
<div class="card-body">
#include('admin.partials.flash', ['$errors' => $errors])
#if (!empty($category))
{!! Form::model($category, ['url' => ['admin/categories', $category->id], 'method' => 'PUT']) !!}
{!! Form::hidden('id') !!}
#else
{!! Form::open(['url' => 'admin/categories']) !!}
#endif
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, ['class' => 'form-control', 'placeholder' => 'category name']) !!}
</div>
<div class="form-group">
{!! Form::label('parent_id', 'Parent') !!}
{!! General::selectMultiLevel('parent_id', $categories, ['class' => 'form-control', 'selected' => !empty(old('parent_id')) ? old('parent_id') : !empty($category['parent_id']) ? $category['parent_id'] : '', 'placeholder' => '-- Choose Category --']) !!}
</div>
<div class="form-footer pt-5 border-top">
<button type="submit" class="btn btn-primary btn-default">Save</button>
Back
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endSection
this is the migration
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->bigInteger('parent_id');
$table->timestamps();
});
}
this is the edit method in controller
public function edit($id)
{
$category = Category::findOrFail($id);
$categories = Category::orderBy('name', 'asc')->get();
$this->data['categories'] = $categories->toArray();
$this->data['category'] = $category;
return view('admin.categories.form', $this->data);
}
you should try save() method.
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$params['slug'] = Str::slug($params['name']);
$params['parent_id'] = (int)$params['parent_id'];
$category = Category::findOrFail($id);
if ($category->save()) {
Session::flash('success', 'Category has been updated.');
}
return redirect('admin/categories');
}
Replace with above one.
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$category = Category::findOrFail($id);
$category->slug = Str::slug($params['name']);
$category->parent_id = (int)$params['parent_id'];
$category->save();
Session::flash('success', 'Category has been updated.');
return redirect('admin/categories');
}
I think your issue is inyour validation rule (specifically in your unique rule). May I suggest something else ?
I don't have the environment to test it right but now, so it may have some tweak to do.
use Illuminate\Validation\Rule;
...
public function rules()
{
$name = [
'required',
Rule::unique('categories')->where(function ($query) {
return $query->where('name', $this->name)
->where('parent_id', $this->parent_id);
})->ignore($this->id, 'id'),
];
$slug = [
Rule::unique('categories', 'slug')->ignore($this->id, 'id'),
];
return [
'name' => $name,
'slug' => $slug,
];
}
So I have a search form for offices and delete for offices, also edit it those 2 were working before. But after I changed and fix edit form and button those are not working anymore the search is not working it shows this error
Undefined variable: building (View: C:\xampp\htdocs\Eguide\resources\views\search.blade.php)
The delete also show this error but it works after I go back to the office page it deleted it but it shows an error message:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\Eguide\resources\views\building.blade.php)
DD offices result
This is the controller for search and delete
OfficeController.php
public function index()
{
$search = \Request::get('search');
$offices = Office::where('name','like','%'.$search.'%')->get();
return view('search',compact('offices','search'));
}
public function store(Request $request, $id)
{
$office = new Office();
$office->name =$request->officename;
$office->floor = $request->floor;
$office->building_id = $id;
$office->save();
\Session::flash('building_flash', 'Created successfully!');
return redirect()->route('building', $id);
}
public function show($id)
{
$office = Office::find($id);
return view('office')->withOffice($office);
}
public function edit($id, $office_id) {
$office = Office::find($office_id);
return view('editoffice', compact('office', 'id'));
}
public function update(Request $request, $id, $office_id)
{
// echo $id.'--'.$office_id;exit;
//$office = Office::find($id);
$office = Office::find($office_id);
$office->name = $request->officename;
$office->floor = $request->floor;
$office->update();
\Session::flash('building_flash', 'Updated successfully!');
return redirect()->route('building', $id);
}
public function destroy($id)
{
$office = Office::find($id);
$office->delete();
\Session::flash('building_flash_delete', 'Deleted successfully!');
return redirect()->route('building', $id);
}
}
search.blade.php
No error in search when I remove this
Edit
<div class="search">
{!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-md">Search
</button>
</span>
</div>
{!! Form::close()!!}
</div>
<hr>
<table class="table">
<thead>
<th>Office Name</th>
<th>Belongs to</th>
<th>Office Floor</th>
</thead>
<tbody>
#foreach($offices as $office)
<tr>
<td>{{optional($office)->name}}</td>
<td>{{$office->building->name}}</td>
<td>{{$office->floor}}</td>
<td class="a">
#if(!Auth::guest())
Edit
Delete
#endif
#endforeach
#endsection
I also have Building.php in app folder it has code like this
class Building extends Model
{
public $table = 'buildings';
public function offices(){
return $this->hasMany('App\Office');
}
}
Office.php
class Office extends Model
{
public function building(){
return $this->belongsTo('App\Building');
}
}
ROUTES
Route::get('/', 'BuildingController#index')->name('index');
Route::get('building/{id}', 'PageController#show')->name('building');
Route::get('office/{id}', 'OfficeController#show')->name('officeMenu');
Route::get('offices', 'OfficeController#index');
Route::group(['middleware' => ['auth']], function () {
Route::get('buildings/create', 'BuildingController#create')->name('createbform');
Route::post('building/create/store', 'BuildingController#saveBuilding')->name('createbuilding');
Route::get('building/{id}/edit', 'BuildingController#edit');
Route::post('building/{id}/edit', 'BuildingController#update')->name('editbuilding');
Route::get('building/{id}/delete', 'BuildingController#destroy');
Route::get('building/{id}/offices/create', 'OfficeController#create')->name('createofficeform');
Route::post('building/{id}/offices/create/store', 'OfficeController#store')->name('createoffice');
Route::get('building/{id}/offices/{office_id}/edit', 'OfficeController#edit')->name('editofficeform');
Route::post('building/{id}/offices/{office_id}/edit', 'OfficeController#update')->name('editoffice');
Route::get('offices/{id}/delete', 'OfficeController#destroy')->name('deleteoffice');
});
buildidng.blade.php
<div class="officebg">
<link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet">
<div class="Bldgttl">
<div class="container">
<div class="row">
<div class="col-lg-12">
<img src="{{URL::to('/assets')}}/{{$building->picture}}" alt="" style="height:300px; width:500px;">
</div>
</div>
<div class="row">
<div class="col-lg-12">
{{$building->name}}
</div>
</div>
</div>
</div>
<div class="rows">
<div class="col-md-6 col-md-offset-3">
<div class="col-xs-4 col-md-6">
#if(!Auth::guest())
Create an Office
#endif
</div>
{!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-md">Search</i>
</button>
</span>
</div>
{!! Form::close()!!}
<table class="table">
<div class="ttitle">
<thead>
<th>Office Name</th>
<th>Office Floor</th>
</thead>
<tbody>
#foreach($offices as $office)
<tr>
<td>{{optional($office)->name}}</td>
<td>{{$office->floor}}</td>
<td class="a">
#if(!Auth::guest())
Edit
Delete
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
#endsection
You don't have a building defined in show.
public function show($id)
{
$office = Office::find($id);
return view('office')->withOffice($office);
}
What you can do is to load a building in show method
public function show($id)
{
$office = Office::find($id);
$building = Building::first();//some logic to find building
return view('office',['building' => $building, 'office' => $office]);
}
Your building.blade.php is trying to access the $building variable. Your show method in your controller is only passing $office as data. Since $building doesn't exist trying to get the name property of it is returning an error.
You need to either pass $building from the controller to the view, or if it is part of $office extrapolate $building from that variable.
public function show($id)
{
$office = Office::find($id);
$building = Buildng::where('id', '=', $office->building_id)->firstOrFail();
return view('office',compact('office', 'building'));
}
Hello i have two models Adress and Kontokorrent they have a one to one relationship. I would like to make a search function and search after Adress and Kontokorrent columns
My models:
Adress Model
class Adress extends Model
{
protected $table = "Adressen";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchAdress($query, $searchTerm)
{
return $query->where('LieferOrt', 'LIKE', '%'.$searchTerm.'%')
->orWhere('Name1', 'LIKE', '%'.$searchTerm.'%')
->orWhere('LieferStrasse', 'LIKE', '%'.$searchTerm.'%');
}
public function kontokorrent()
{
return $this->hasOne(Kontokorrent::class, 'Adresse');
}
}
Kontokorrent Model
class Kontokorrent extends Model
{
protected $table = "Kontokorrent";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchKto($query, $searchTerm)
{
return $query->where('Kto', 'LIKE', '%'.$searchTerm.'%');
}
public function adress()
{
return $this->belongsTo(Adress::class, 'Adresse');
}
}
Controller
class AdressesController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$adresses = Adress::whereHas('kontokorrent', function($query) use($searchTerm) {
$query->where('KtoArt', 'D')
->searchKto('K75688'); // this is working
// -> searchKto($searchTerm); this is NOT working
})->orderBy('Name1')
->searchAdress($searchTerm)
->paginate(60);
return view('adresse.index', compact('adresses', 'searchTerm'));
}
}
The search function in Adress model is working. Now i would like to search after the customer ID (Kto) in Kontokorrent. So i made a scope in Kontokorrent and chain it to the contoller search function.
->searchKto('K75688') .... this is working i get a result
->searchKto($searchTerm) .... this is not working when i entry the customer id in my input field and hit enter. I get a 0 row table.
View
#section('content')
<div class="row">
<div class="col-xs-12 col-md-12">
<form role="search" method="GET" action="/adresses">
<div class="input-group">
<input type="text" class="form-control" name="searchTerm" value="{{ isset($searchTerm) ? $searchTerm : '' }}" placeholder="Suche nach Name, Straße, Ort">
<div class="input-group-btn">
<button type="submit" class="btn btn-search btn-default">
Suchen...
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Straße</th>
<th>Ort</th>
<th>PLZ</th>
<th>Land</th>
</tr>
</thead>
<tbody>
#if(count($adresses) > 0)
#foreach($adresses as $adress)
<tr>
<th scope="row">{{ $loop->iteration }}</th>
<td>
{{$adress->Anrede}} {{ $adress->Name1}}
#if($adress->kontokorrent)
<small>{{ $adress->kontokorrent->Kto }}</small>
#endif
</td>
<td>{{ $adress->LieferStrasse }}</td>
<td>{{ $adress->LieferOrt }}</td>
<td>{{ $adress->LieferPLZ }}</td>
<td>{{ $adress->LieferLand }}</td>
</tr>
#endforeach
#else
<tr><td colspan="6" class="text-center">Kein Eintrag gefunden.</td></tr>
#endif
</tbody>
</table>
</div>
</div>
{{ $adresses->appends(['searchTerm' => $searchTerm])->links() }}
#endsection
I don't understand why I get an empty table.
i have 2 tables.
users (name, username, email, password, remember_token)
dosen (iddosen, namedosen, address, phonenumber)
i want to show data from 2 tables in 1 view.
my User model :
public function profildosen()
{
return $this->belongsTo('App\Dosen');
}
Dosen model :
public function user()
{
return $this->hasOne('App\User');
}
view :
#foreach($dosen as $key => $value)
<strong>Kode Dosen :</strong> {{ $value->profildosen->iddosen }}<br>
<strong>Nama :</strong> {{ $value->profildosen->namedosen}}<br>
<strong>Alamat :</strong> {{ $value->profildosen->address}}<br>
<strong>No HP :</strong> {{ $value->phonenumber}} <br>
<strong>Email :</strong> {{ $value->email }}<br>
#endforeach
method :
$dosen = User::paginate(5);
return view('admin/dosen.index', compact('dosen'));
and got error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'dosen.id' in 'where clause' (SQL: select * from `dosen` where `dosen`.`id` is null limit 1) (View: D:\XAMPP\htdocs\infodosenku\resources\views\admin\dosen\index.blade.php)
what is the right method ?
UPDATE
Scheme Database
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('username');
$table->string('email')->unique();
$table->string('password', 60);
$table->boolean('admin')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::create('dosen', function (Blueprint $table) {
$table->string('id');
$table->string('user_id');
$table->string('nipy');
$table->string('namadosen');
$table->string('alamatdosen');
$table->integer('notelpdosen');
$table->timestamps();
});
Route :
Route::resource('/admin/dosen', 'AdminController',
['except' => ['show']]);
Controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Request;
use App\Http\Requests;
use App\Http\Requests\CreateDosenRequest;
use App\Dosen;
use App\User;
use Illuminate\Support\Facades\Input;
use DB;
class AdminController extends Controller
{
public function index()
{
// ambil semua data dosen
$dosen = User::paginate(5);
return view('admin/dosen.index', compact('dosen'));
}
public function create()
{
return view('admin/dosen.create');
}
public function store(CreateDosenRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => bcrypt($request->input['password']),
'admin' => $request->input('admin')
]);
$dosen = Dosen::create([
'id' => $request->input('iddosen'),
'nipy' => $request->input('nipy'),
'namadosen' => $user->name,
'user_id' => $user->id,
'alamatdosen' => $request->input('alamatdosen'),
'notelpdosen' => $request->input('notelpdosen'),
]);
return redirect('admin/dosen')->with('message', 'Data berhasil ditambahkan!');
}
public function show($id)
{
$dosen = User::find($id);
return view('admin/dosen/show', compact('dosen'));
}
public function edit($id)
{
$dosen = User::find($id);
return view('admin.dosen.edit', compact('dosen'));
}
public function update($id)
{
$dosenUpdate = Request::all();
$dosen = User::find($id);
$dosen->update($dosenUpdate);
return redirect('admin.dosen')->with('message', 'Data berhasil diubah!');
}
public function destroy($id)
{
User::find($id)->delete();
return redirect('admin.dosen')->with('message', 'Data berhasil dihapus!');
}
}
And my View :
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Daftar Dosen</div>
<div class="panel-body">
<form class ="form-inline" action="{{ URL('/dosen/hasil/') }}" action="GET">
<div class="form-group">
<label for="cari">Cari Dosen </label>
<input type="text" class="form-control" id="cari" name="cari" placeholder="Masukan Nama Dosen">
</div>
<input class="btn btn-primary" type="submit" value="Cari">
</form><br>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Nama</td>
<td>username</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
#foreach($dosen as $key => $value)
<tr>
<td>{{ $value->name }}</td>
<td>{{ $value->username}}</td>
<td>
{!! Form::open(['url' => 'dosen/' . $value->id . '/edit', 'style'=>'display:inline-block']) !!}
{!! Form::hidden('_method', 'GET') !!}
{{ Form::button('<i class="fa fa-pencil-square-o"></i>', ['type' => 'submit', 'class' => 'btn btn-warning', 'title' => 'Ubah'] ) }}
{!! Form::close() !!}
<button title="Tampilkan" type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal-{{ $value->id }}"><i class="fa fa-share"></i></button>
<!-- Modal -->
<div class="modal fade" id="myModal-{{ $value->id }}" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">{{ $value->namadosen }}</h4>
</div>
<div class="modal-body" style="overflow:auto;">
<strong>Kode Dosen :</strong> {{ $value->dosen->id }}<br>
<strong>NIP/NIPY :</strong> {{ $value->nipy }}<br>
<strong>Nama :</strong> {{ $value->namadosen }}<br>
<strong>Alamat :</strong> {{ $value->alamatdosen }}<br>
<strong>No HP :</strong> {{ $value->notelpdosen }} <br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{!! Form::open(['url' => 'dosen/' . $value->id, 'style'=>'display:inline-block']) !!}
{!! Form::hidden('_method', 'DELETE') !!}
{{ Form::button('<i class="fa fa-trash"></i>', ['type' => 'submit', 'class' => 'btn btn-danger', 'title' => 'Hapus'] ) }}
{!! Form::close() !!}
{!! Form::model($value, ['route' => ['admin.dosen.update', $value->id], 'method' => 'PUT']) !!}
</td>
</tr>
#endforeach
</tbody>
</table>
<h5><span class="label label-default">
Showing {!! $dosen->count() !!} results from total {!! $dosen->total() !!} results.
</span></h5>
<div> {!! $dosen->links() !!} </div>
</div>
</div>
</div>
</div>
</div>
#endsection
Dosen Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Dosen extends Model
{
protected $table = 'dosen';
protected $fillable = ['iddosen', 'namadosen', 'user_id', 'nipy', 'kodeprogdidosen','alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen', 'agamadosen', 'emaildosen', 'sandidosen', 'jkldosen', 'fotodosen'];
protected $casts = [
'iddosen' => 'varchar',
];
public function dosen()
{
return $this->belongsTo('App\Dosen');
}
}
User Model :
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'username', 'email', 'password', 'admin',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profildosen()
{
return $this->belongsTo('App\Dosen');
}
}
From Laravel Docs
Eloquent determines the default foreign key name by examining the name
of the relationship method and suffixing the method name with _id.
Your function name is profiledosen so Laravel will assume that in your in your Dosen Table you have id field as primary identifier.
You can change it from iddosen to id only and then change your method name to
public function dosen()
{
return $this->belongsTo('App\Dosen');
}
Alternatively you can supply the custom primary key to your method like
public function profildosen()
{
return $this->belongsTo('App\Dosen', 'iddosen');
}
The reason is that you badly identify your table id a so instead of dosen.id you should use dosen.iddosen
So the query should be like this: select * from dosen where iddosen is null limit 1
Or you may to use Laravel Query Builder More.
But the most important thing is that you need to know on what columns you will join your tables.
Hope it will help