laravel error to get data from database - laravel

i new in laravel development,
i have code problem.
i have MotorsController.php like this
class MotorsController extends BaseController{
protected $motor;
public function __construct(Motor $motor){
$this->motor = $motor;
}
public function index(){
$motors=$this->motor->with('motorcategory', 'motorcolor')->get();
return View::make('motors.index', compact('motors'));
}
and i have model like below
Motor.php
<?php
class Motor extends Eloquent {
protected $table = 'motors';
protected $guarded = array();
public function motorcategory(){
return $this->belongsTo('MotorCategory');
}
public function motorcolor(){
return $this->belongsTo('MotorColor');
}
public static $rules = array(
'name' => 'required',
'police_number' => 'required',
'sex' => 'required'
);
}
and MotorCategory.php
<?php
class MotorCategory extends Eloquent {
public function motor(){
return $this->hasMany('Motor');
}
}
and MotorColor.php
class MotorColor extends Eloquent {
public function motor(){
return $this->hasMany('Motor');
}
}
in motors.index i want to get motor data which have relation with table motorcolor and motorcategory,
but now i still have error like:
ErrorException (E_UNKNOWN)
Trying to get property of non-object (View: C:\Users\LalatTempur\Laravel\ironhorse\app\views\motors\index.blade.php)
i hope someone can help me..
by the way,, sorry for my english :)
my motors.index
<tbody>
#foreach ($motors as $motor)
<tr>
<td>{{ $motor->name }}</td>
<td>{{ $motor->police_number }}</td>
<td>{{ $motor->motor_category->name }}</td>
<td>{{ $motor->motor_color->name }}</td>
<td>{{ $motors->purchase_date}}</td>
<td>{{ $motors->status }}</td>
<td>
{{ link_to_route('motors.show', 'Detail', array($motor->id), array('role' =>'btn', 'class' => 'btn btn-primary btn-xs')) }} |
{{ link_to_route('motors.edit', 'Edit', array($motor->id), array('role' =>'btn', 'class' => 'btn btn-info btn-xs')) }} |
<!-- {{ link_to_route('members.destroy', 'Delete', array($member->id), array('role' =>'btn', 'class' => 'btn btn-danger btn-xs')) }} -->
<!-- </td>
<td> -->
{{ Form::open(array('method' => 'DELETE', 'route' => array('motors.destroy', $motor->id), 'style'=>'display:inline;' )) }}
{{ Form::submit('Delete', array('class' => 'btn btn-danger btn-xs ')) }}
{{ Form::close() }}
</td>
</tr>
#endforeach
</tbody>

You are accidently using the plural of motor inside your foreach:
<td>{{ $motors->purchase_date}}</td>
<td>{{ $motors->status }}</td>
Should be:
<td>{{ $motor->purchase_date}}</td>
<td>{{ $motor->status }}</td>
Although the error message doesn't really fit well, because a collection would be an object too.

Related

Unique Data in Laravel

I have data like this
How to validate, if the user chooses same Kode, or user chooses a Kode that has conflicting Hari or Jam.
My Controller
public function store(Request $request)
{
$validate = Validator::make($request->all(), [
'kode_matkul' => 'required',
]);
if($validate->fails()) {
return response()->json(['errors' => $validate->errors()]);
}
}
My View Blade
<tbody>
#foreach ($mapel as $row)
<tr>
<td class="text-center">{{ $row->course }}</td>
<td>{{ $row->course_name }}</td>
<td class="text-center">{{ $row->sks }}</td>
<td class="text-center">{{ $row->kelompok }}</td>
<td>{{ $row->name }}</td>
<td class="text-center">{{ $row->hari }}</td>
<td class="text-center">{{ date('H:i', strtotime($row->start_time)) . ' - ' . date('H:i', strtotime($row->end_time)) }}</td>
<td class="text-center">{{ $row->ruangan }}</td>
<td class="text-center">
<input class="form-check-input" type="checkbox" name="kode_matkul[]" id="kode_matkul" value="{{ $row->course }}">
</td>
</tr>
#endforeach
</tbody>
Thank you
Please refer to https://laravel.com/docs/9.x/validation#form-request-validation for more information, but basically your steps would be -
create a store request for mapel (i guess?) with something like -
php artisan make:request StoreMapelRequest
In this newly create store request, you should create a rule for uniqueness to your desired fields -
public function rules()
{
return [
'Kode' => 'required|unique:mapels|max:255',
'Hari' => 'required|unique:mapels|max:255',
'Jam' => 'required|unique:mapels|max:255',
];
}
Edit: You can also add a simple |unique on your current store request, like this -
public function store(Request $request)
{
$validate = Validator::make($request->all(), [
'kode_matkul' => 'required|unique:mapels',
]);
if($validate->fails()) {
return response()->json(['errors' => $validate->errors()]);
}
}
Please notice that I assume that your table name is 'mapels', in which you are seeking this uniqueness rule.

How to access map function in Laravel

This is my controller code:
public function RentCertificate()
{
$report = Report::distric()->status(1)->desk(15)->get()
->groupBy(function (Report $item) {
return $item->created_at->format('Y-m');
})
->map(function($rows, $key) {
return [
'column_one' => $rows->column_one,
'rows' => $rows
];
});
return view('adcr.report.rent_certificate', compact('report'));
}
when I try
#foreach($report as $key => $data)
<tr role="row" class="odd">
<td class="input_bangla">{{ $key+1 }}</td>
<td>{{ $data->fiscal_year }}</td>
<td>{{ $data->month }}</td>
</tr>
#endforeach
I got:
Property [fiscal_year] does not exist on this collection instance.
How can I access this data?
Here,
#foreach($report as $key => $data)
$data is the array you've mapped. An array like ['column_one' => ..., 'rows' => ...], it's not an object. You need to access one of its keys (column_one or rows).
Also, you can use a ternary operator with loop iteration to assign the classes even or odd in your <tr> element.
#foreach($report as $key => $data)
<tr role="row" class="{{ ($loop->iteration % 2) ? 'even' : 'odd' }}">
<td class="input_bangla">{{ $key+1 }}</td>
<td>{{ $data['rows']->fiscal_year }}</td>
<td>{{ $data['rows']->month }}</td>
</tr>
#endforeach

Laravel Livewire strange table rendering behavior

I have a table component in my page that renders a list of users, and one of the columns in the table is the user's role. when I paginate through the table of users, livewire is randomly inserting a row in the table for the role, like it's somehow getting confused and including the relationship in the loop, instead of just the main model.
This is the result after paginating:
Here's what it's doing to the markup:
It only happens the first time the page is loaded and I click one of the pagination buttons. It will randomly happen on one or more pages as I paginate through the table, but once I reach the end, I can paginate through every page any number of times without seeing it again until I refresh the page.
Here is my User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, SoftDeletes, CanResetPassword, HasFactory;
protected $with = ['role'];
public function role()
{
return $this->belongsTo(Role::class);
}
}
Here's my Role model:
class Role extends Model
{
use HasFactory, SoftDeletes;
public function user()
{
return $this->hasOne(User::class);
}
}
My Livewire UserListComponent, which is a full-page component:
class UserListComponent extends Component
{
use WithPagination;
public $search;
public $roles;
public $user;
protected $paginationTheme = 'bootstrap';
protected $listeners = ['refreshUsers' => '$refresh'];
public function mount()
{
$this->search = '';
}
public function render()
{
return view('livewire.users.index', [
'users' => User::withTrashed()->search(['first_name', 'last_name'], $this->search)->paginate(5)
]);
}
public function show($id)
{
return redirect()->route('users.edit', ['user' => $id]);
}
}
My blade view:
<x-table search="true">
#slot('head')
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
#endslot
#slot('body')
#forelse($users as $user)
<x-table.row id="{{ $user->id }}" includeStatus="true" :status="$user->deleted_at">
<td>{{ $user->id }}</td>
<td>{{ $user->first_name }}</td>
<td>{{ $user->last_name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role->name }}</td>
</x-table.row>
#empty
<x-table.empty-row colSpan="6" />
#endforelse
#endslot
#slot('paginationLinks')
{{ $users->links() }}
#endslot
</x-table>
And here's the table component content:
#props(['search' => false, 'paginationLinks' => false])
<div class="table-responsive">
<div class="d-flex flex-row justify-content-between">
<div class="col-md-3"></div>
<div class="col-md-2">
#if ($search)
<input wire:model="search" placeholder="Search" type="text" class="form-control">
#endif
</div>
</div>
<table class="table">
<thead>
<tr>
{{ $head }}
</tr>
</thead>
<tbody>
{{ $body }}
</tbody>
</table>
<div class="mt-4">
#if ($paginationLinks)
{{ $paginationLinks }}
#endif
</div>
</div>
And the table row component:
#props(['includeStatus' => false, 'status' => false, 'id'])
<tr wire:key="{{ $id }}" wire:loading.class.delay="opacity-50" wire:target="search" wire:click="show({{ $id }})">
{{ $slot }}
#if ($includeStatus)
<td>
#if ($status)
<span class=" ms-2 badge bg-danger">Inactive</span>
#else
<span class="ms-2 badge bg-success">Active</span>
#endif
</td>
#endif
</tr>

ErrorException (E_ERROR) Undefined variable: userdata

The error message I get is:
ErrorException (E_ERROR) Undefined variable: userdata
I know these things get asked a lot. I have searched Google and here and I have already tried suggested answers to no avail.
Controller:
public function index()
{
$userdata = EditUserModel::all()->paginate(5);
return view('admin.userman')->with(['userdata' => $userdata])->with('i', (request()->input('page', 1) - 1) * 5);
}
Route:
Route::resource('admin.userman', 'EditUserController');
Model:
public class EditUserModel extends Model
{
public $table = "users";
protected $fillable = [
'id',
'name',
'email',
'role',
'password'
];
}
View:
#foreach($userdata as $data)
<tbody>
<tr>
<td>{{ $data->id }}</td>
<td>{{ $data->email }}</td>
<td>{{ $data->created_at }}</td>
<td>{{ $data->role }}</td>
<td>{{ $data->status }}</td>
<td>
Edit
</td>
<td>
#csrf
#method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</td>
</tr>
</tbody>
#endforeach
The output should be a table listing the contents of the users table from the database. but i'm getting undefined variable error.
You should try this:
Controller:
public function index()
{
$userdata = EditUserModel::all()->paginate(5);
$i = (request()->input('page', 1) - 1) * 5;
return view('admin.userman',compact('userdata','i'));
}
Route:
Route::resource('admin.userman', 'EditUserController');
Model:
public class EditUserModel extends Model
{
public $table = "users";
protected $fillable = [
'id',
'name',
'email',
'role',
'password'
];
}
View:
#if(isset($userdata))
#foreach($userdata as $data)
<tbody>
<tr>
<td>{{ $data->id }}</td>
<td>{{ $data->email }}</td>
<td>{{ $data->created_at }}</td>
<td>{{ $data->role }}</td>
<td>{{ $data->status }}</td>
<td>
Edit
</td>
<td>
#csrf
#method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</td>
</tr>
</tbody>
#endforeach
#endif
public function index()
{
$userdata = EditUserModel::all()->paginate(5);
$page = array('i'=>(request()->input('page', 1) - 1) * 5);
return view('admin.userman',compact('userdata','page'));
}

Laravel Pgination not working when putting link after foreach

I am using laravel 5.2 and I am facing some issue with pagination link. When I am adding this code:
{{ $wachat->links() }}
After foreach I am getting this error:
Call to undefined method Illuminate\Database\Query\Builder::links() (View: /Applications/MAMP/htdocs/kc/kyo-webservice/resources/views/wechat/show.blade.php)
In my controller I am using this code:
public function wechatshows($d1, $id, $name, Request $request)
{
$users = Keyuser::where('imception_id', '=', $d1)->first();
$user = UserKey::where('id', '=', $id)->first();
if ($name == "all") {
$wachat = Wechat::where('key', '=', $d1)->orderBy('id', 'DESC')->paginate(5);
} else {
$wachat = Wechat::where('key', '=', $d1)->where('groupName', '=', $name)->orderBy('id', 'DESC')->paginate(5);
}
$wechatcontact = Wechat::select('groupName')->groupBy('groupName')->get();
return view('wechat.show', ['wachat' => $wachat, 'user' => $user, 'product' => $d1, 'users' => $users, 'keyUser' => $d1, 'wechatcontact' => $wechatcontact]);
}
I am using this code in my views:
<tbody id="chatListBody" style="overflow-y: scroll;">
#foreach ($wachat as $wachat)
<tr>
<input type="hidden" class="wechatname" data-id="{{ $wachat->id }}">
<td>{{ $wachat->id }}</td>
<td>{{ $wachat->wxid }}</td>
<td>{{ $wachat->username }}</td>
#if ($wachat->type === 'image')
<td><a class="example-image-link" href="{{ url('/images/'.$wachat->imgPath.'') }}" data-lightbox="{{$wachat->imgPath}}"
data-title="{{$wachat->imgPath}}"><img class="imgwhatsapp" data-lightbox="roadtrip" src="{{ url('/images/'.$wachat->imgPath.'') }}"></a></td>
#elseif ($wachat->type === 'video')
<td>{{$wachat->imgPath}}</td>
#elseif ($wachat->type === 'audio')
<td> {{$wachat->imgPath}} </td>
#elseif ($wachat->type === 'text')
<td>{{$wachat->message}}</td>
#else
<td>no data</td>
#endif
<td>{{ $wachat->created_at }}</td>
</tr>
#endforeach
</tbody>
{{ $wachat->links() }}
</div>
</table>
When I am putting {{ $wachat->links() }} above foreach it is working I don't know why it is happening.
Perhaps, $wachat is getting override inside #foreach($wachat as $wachat). so, it can not find links() method.
you should use #foreach($wachat as $singleWachat) or as per your convenience.
When you loop through your collection, Your collection become object. After the loop when you do {{ $wachat->links() }}. Your Code try to paginate a object and error shown.
Avoid this kind of problem try to use your collection variable name plural and your object name singular.
public function wechatshows($d1, $id, $name, Request $request)
{
$users = Keyuser::where('imception_id', '=', $d1)->first();
$user = UserKey::where('id', '=', $id)->first();
if ($name == "all") {
$wachats = Wechat::where('key', '=', $d1)->orderBy('id', 'DESC')->paginate(5);
} else {
$wachats = Wechat::where('key', '=', $d1)->where('groupName', '=', $name)->orderBy('id', 'DESC')->paginate(5);
}
$wechatcontact = Wechat::select('groupName')->groupBy('groupName')->get();
return view('wechat.show', ['wachats' => $wachats, 'user' => $user, 'product' => $d1, 'users' => $users, 'keyUser' => $d1, 'wechatcontact' => $wechatcontact]);
}
and
<tbody id="chatListBody" style="overflow-y: scroll;">
#foreach ($wachats as $wachat)
<tr>
<input type="hidden" class="wechatname" data-id="{{ $wachat->id }}">
<td>{{ $wachat->id }}</td>
<td>{{ $wachat->wxid }}</td>
<td>{{ $wachat->username }}</td>
#if ($wachat->type === 'image')
<td><a class="example-image-link" href="{{ url('/images/'.$wachat->imgPath.'') }}" data-lightbox="{{$wachat->imgPath}}"
data-title="{{$wachat->imgPath}}"><img class="imgwhatsapp" data-lightbox="roadtrip" src="{{ url('/images/'.$wachat->imgPath.'') }}"></a></td>
#elseif ($wachat->type === 'video')
<td>{{$wachat->imgPath}}</td>
#elseif ($wachat->type === 'audio')
<td> {{$wachat->imgPath}} </td>
#elseif ($wachat->type === 'text')
<td>{{$wachat->message}}</td>
#else
<td>no data</td>
#endif
<td>{{ $wachat->created_at }}</td>
</tr>
#endforeach
</tbody>
{{ $wachats->links() }}
</div>
</table>

Resources