Property missing in laravel - php

I have setup my localhost to new PC. After import the database to phpmyadmin, I run laravel and open the page. However, I got this error:
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\inventoryApp\resources\views\Item\edit.blade.php)
On the other page, I got this error:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\inventoryApp\resources\views\Item\show.blade.php)
My view code looks like:
<table id="sale-table" class="table table-bordered table-striped table-hover datatable">
<thead>
<tr>
<th>No</th>
<th>Seller</th>
<th>Item ID</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Total Sale</th>
<th>Detail</th>
<th>Action</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($sales as $sale)
<tr>
<td>{{ $sale->id }}</td>
<td>{{ $sale->user->name }}</td>
<td>{{ $sale->item_id }}</td>
<td>{{ $sale->item->name }}</td>
<td>{{ $sale->quantity }}</td>
<td>RM {{ $sale->price }}</td>
<td>{{ $sale->created_at }}</td>
#if(Auth::user()->type=='admin'||Auth::user()->type=='super_admin')
<td class="center">
<i class="glyphicon glyphicon-edit"></i> EDIT
</td>
<td class="center">
<form action="{{ route('Sale.destroy', ['id'=>$sale->id ]) }}" method="post" onsubmit="return confirm('Delete sale {{ $sale->name }} permanently?')" >
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button class="btn btn-danger btn-sm" type="submit" ><i class="glyphicon glyphicon-trash"></i> DELETE</button>
</form>
</td>
#else
<td class="center">
<b><p>Only for admin</p></b>
</td>
<td class="center">
<b><p>Only for admin</p></b>
</td>
#endif
</tr>
#endforeach
</tbody>
</table>
My controller is:
class SalesController extends Controller
{
public function index()
{
$sales=Sale::all();
return view('Sale.index')->with('sales',$sales);
}
public function create()
{
$items=Item::all();
return view('Sale.create')->with('items',$items);;
}
public function store(Request $request)
{
$this->validate($request, [
'item_id'=>'required|integer',
//'price'=>'required|regex:/^\d+(\.\d{1,2})?$/',
'quantity'=>'required|integer',
]);
$item=Item::FindOrFail($request->item_id);
$item->quantity -= ($request->quantity);
$sale=new Sale;
$sale->seller_id=$request->get('seller_id');
$sale->item_id=$item->id;
$sale->price=$item->selling_price * $request->input('quantity');
$sale->quantity=$request->input('quantity');
$sale->save();
$item->save();
return redirect('/Sale')->with('success','Sale added');
}
public function edit($id)
{
$sales=Sale::find($id);
return view('Sale.edit')->with('sales',$sales);
}
public function update(Request $request, $id)
{
$this->validate($request, [
//'price'=>'required|regex:/^\d+(\.\d{1,2})?$/',
'quantity'=>'required|integer',
]);
$sale=Sale::find($id);
$item=Item::FindOrFail($sale->item_id);
$item->quantity = $item->quantity + $sale->quantity - $request->quantity;
$sale->quantity=$request->input('quantity');
$sale->price=$item->selling_price * $request->input('quantity');
$item->save();
$sale->save();
return redirect('/Sale')->with('success','Sale updated');
}
public function destroy($id)
{
$sale = Sale::find($id);
$sale->delete();
return redirect('/Sale')->with('success','Sale Removed');
}
}
When I try to add a new item, it works well. But I cannot use the imported one.

Make sure you have id column in your sale table.
and you have create the relationship with your user model and item model in your migration file and sale model.
public function user()
{
return $this->belongsTo(User::class);
}
public function item()
{
return $this->belongsTo(Item::class); // assuming you have named the model "Item" for your item table.
}

Related

The delete button never return or redirect (never responds)

First I had to click on a delete button but it returns nothing, I don't know why.
It must go to a delete function on invoicesController.php file and do whatever I want to do.
This is my invoices controller to return all invoices:
public function index()
{
$invoice = invoices::all();
return view('invoices.invoice')->with('in', $invoice);
}
And this is my blade table:
<table id="example" class="table key-buttons text-md-nowrap">
<thead>
<tr>
<th class="border-bottom-0">#</th>
<th class="border-bottom-0">رقم الفاتورة</th>
<th class="border-bottom-0">تاريخ الفاتورة</th>
<th class="border-bottom-0">تاريخ الاستحقاق</th>
<th class="border-bottom-0">المنتج</th>
<th class="border-bottom-0">القسم</th>
<th class="border-bottom-0">الخصم</th>
<th class="border-bottom-0">نسبة الضريبة</th>
<th class="border-bottom-0">قيمة الضريبة</th>
<th class="border-bottom-0">الاجمالي</th>
<th class="border-bottom-0">الحالة</th>
<th class="border-bottom-0">ملاحظات</th>
<th class="border-bottom-0">العمليات</th>
<th></th>
</tr>
</thead>
<tbody>
#php
$a=0;
#endphp
#foreach ($in as $i)
<tr>
<td>{{ $a++ }}</td>
<td>{{ $i->invoice_number }}</td>
<td>{{ $i->invoice_date }}</td>
<td>{{ $i->due_date }}</td>
<td>{{ $i->product }}</td>
<td>
{{ $i->section->section_name }}
</td>
<td>{{ $i->discount }}</td>
<td>{{ $i->rate_vat }}</td>
<td>{{ $i->value_vat }}</td>
<td>{{ $i->total }}</td>
<td>
#if ($i->value_status == 1)
<span class="text-status">{{ $i->status }}</span>
#elseif($i->value_status == 2)
<span class="text-danger">{{ $i->status }}</span>
#else
<span class="text-warning">{{ $i->status }}</span>
#endif
</td>
<td>{{ $i->note }}</td>
<td>
edit
this is the issue
<form action="{{ route('in.delete' , $i->id) }}" method="get">
#csrf
<input type="hidden" value="{{ $i->id }}">
<button type="button">delete</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
Here is my delete function from invoicesController:
public function delete(Request $request)
{
dd($request);
}
My web.php:
Route::post('in/{id}', [App\Http\Controllers\InvoicesController::class, 'delete'])
->name('in.delete');
First of all, change your web.php route from post to delete:
Route::delete('in/{id}', [App\Http\Controllers\InvoicesController::class, 'delete'])
->name('in.delete');
Second, change your form method from get to POST:
<form action="{{ route('in.delete', $i->id) }}" method="POST">
And lastly, after that exact <form> tag and before #csrf, add a new blade directive that will "simulate" you are sending this form as DELETE:
<form action="{{ route('in.delete', $i->id) }}" method="POST">
#method('DELETE')
#csrf
You can read more about #method here.

How to get the name of user through relations in Laravel

I want to implement simple teaming option to my app. I have theese tables:
users/teams /team_members/
-----/---------/------------/
id /id /id /
name /user_id /user_id /
... /... /team_id /
I have 3 models where I have defined relations:
User model:
public function teams() {
return $this->hasOne(Team::class);
}
public function teamMembers() {
return $this->hasManyThrough(Team::class, TeamMembers::class);
}
Team model:
public function user() {
return $this->belongsTo(User::class);
}
public function members() {
return $this->hasMany(TeamMember::class);
}
TeamMember model:
public function user() {
return $this->belongsTo(User::class);
}
User can only create one team, but join many teams. The problem I have is with displaying data in the frontend.
This is the query I make in the controller:
public function index(User $user) {
$teams = Team::where('user_id', auth()->user()->id )->with('members')->get();
return view('teams.index')->with('teams', $teams);
}
I have a table with the members of the current autheticated user team. I want to display the names if each member but the only thing i can do is $team->member->id and I get the ids of the users but I want to get their names too. I can do it with simple query but I dont want to make new query for every row.
This is the blade file:
#if ( $teams->count() > 0 )
#foreach ($teams as $team)
<table class="table table-striped table-sm table-responsive-lg">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Members</th>
<th scope="col">Created</th>
<th scope="col" colspan="2"></th>
</tr>
</thead>
<tbody>
<tr>
<td>{{$team->name}}</td>
<td>{{ $team->members->count('members')}} {{ Str::plural('member', $team->id) }}</td>
<td>{{ $team->created_at->diffForHumans() }}</td>
<td>
Edit
</td>
<td>
<form action="" method="POST">
#method('DELETE')
#csrf
<button class="btn btn-sm btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
</tbody>
</table>
<br>
<h5>Team members:</h5>
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Added</th>
</tr>
</thead>
<tbody>
#foreach ($team->members as $member)
<tr>
<td>{{ $member->user->name }}</td>
<td>{{ $member->created_at->diffForHumans() }}</td>
</tr>
#endforeach
</tbody>
</table>
#endforeach
#else
<div class="container">
<h2>You do not own a team</h2>
<p class="lead text-muted">You can create your own team or join the team of other user.</p>
<p>
Create team
Join team
</p>
</div>
#endif
When I changed $team->member->id with $member->user->name it worked. It shows the names of the users but I get N+1 queries alert and I don't know how to fix it (i tried different queries and relations but it didnt work):
You are accessing the user relationship from each member. So lets eager load that relationship as well.
public function index(User $user)
{
$teams = Team::where('user_id', auth()->user()->id )->with('members.user')->get();
return view('teams.index')->with('teams', $teams);
}

Laravel Blade not showing data from controller

I want to show data in tabular form in Laravel Blade View. Now, data is not showing up in blade, but when I check in controller using print_r it shows up Following is the code for Controller:-
public function index(){
$pickup = PickupLocation::select('*')
->whereNull('deleted_at')
->get()
->toArray();
$page = 'pickup_locations';
return view('backEnd.pickupManagement.index',compact('page'));
}
Following is the code in web.php:-
Route::match(['get','post'],'pickup-locations','backEnd\pickupManagement\PickupController#index');
And following is the code I am using View:-
<div class="table-responsive">
<table id="zero_config" class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Contact Number</th>
<th>Address</th>
<th width="13%">Action</th>
</tr>
</thead>
<tbody>
#if(!empty($pickup))
#foreach($pickup as $key=>$value)
<tr>
<td>{{ ucfirst($value['name']) }}</td>
<td>{{ ucfirst($value['contact_no']) }}</td>
<td>{{ $value['location'] }}</td>
<td>
<i class="fa fa-edit"></i>
<i class="fa fa-trash"></i>
</td>
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
add $pickup variable as second argument in your compact method.
Try like this
return view('backEnd.pickupManagement.index',compact('page', 'pickup')); }
Happy codding

Laravel - ErrorException Undefined variable

I have tried to refer all the possible solutions in stackoverflow but could not solve this.
This is my Controller.
public function getMessages(){
$messages = Message::all()->toArray();
return View('admin.thesis', ['messages' => $messages]);
}
This is my route/web.php
Route::get ('/thesis','MessagesController#getMessages');
And this is my view
<div class="panel-heading">Thesis Details</div>
<div class="panel-body">
<table class="table table-bordered">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>E-Mail</th>
<th>Contact</th>
<th>State</th>
<th>Country</th>
<th>Article</th>
<th>Author</th>
<th>Uploaded File</th>
</tr>
#foreach($messages as $row)
<tr>
<td>{{$row['firstName']}}</td>
<td>{{$row['lastName']}}</td>
<td>{{$row['email']}}</td>
<td>{{$row['contactNumber']}}</td>
<td>{{$row['state']}}</td>
<td>{{$row['country']}}</td>
<td>{{$row['article']}}</td>
<td>{{$row['author']}}</td>
<td>
<a href="{{ URL::to('/') }}/uploads/{{$row['file_path']}}">
{{$row['file_path']}}
</a>
</td>
</tr>
#endforeach
</table>
</div>
</div>
This is my error
ErrorException
Undefined variable: messages (View:
C:\xampp\htdocs\fileupload\resources\views\admin\thesis.blade.php)
How do I resolve this?
Try this on your Controller
public function getMessages(){
$messages = Message::all();
return view('admin.thesis')->with(['messages' => $messages]);
}
And in your blade file
#foreach($messages as $row)
<tr>
<td>{{ $row->firstName }}</td>
<td>{{ $row->lastName }}</td>
<td>{{ $row->email }}</td>
<!-- etc... -->
<td>
<a href="{{ URL::to('/') }}/uploads/{{ $row->file_path }}">
{{ $row->file_path }}
</a>
</td>
</tr>
#endforeach
Try this on your Controller
public function getMessages(){
$messages = Message::all()->toArray();
return view('admin.thesis', compact('messages'));
}
I used following code and its work for me :
class SidebarController extends Controller
{
public function news_widget() {
$posts = Post::take(5)->orderBy('updated_at', 'DESC')->take();
return view('index', array('data'=>$posts));
}
}
And within the view I simply use $data and its working fine for me.

Laravel 5 Call to undefined method Illuminate\Database\Query\Builder::method()

I have projects which hasMany users, and users belongsTo a project.
I want to count the total amount of users a project has so I need to link them.
This way I'm getting a Call to undefined method Illuminate\Database\Query\Builder::user() error.
What am I doing wrong?
Controller:
class ProjectController extends Controller
{
private $project;
public function __construct(Project $project){
$this->project = $project;
// $this->project = $project
// ->with('user');
}
public function index(Project $project)
{
$projects = $project->with('user')->get();
$currenttime = Carbon::now();
// return view('project.index', array('projects' => $projects, 'currenttime' => $currenttime));
return view('user.index', compact('projects'));
}
}
Model user:
public function project(){
return $this->belongsTo('App\Project', 'project_id','id');
}
Model project:
public function users() {
return $this->hasMany('App\User', 'id');
}
HTML/Blade:
#if(isset($projects))
<table class="table table-striped table-hover table-dynamic datatable">
<thead>
<tr>
<th>{{ trans('common.project') }}</th>
<th>{{ trans('common.workers') }}</th>
<th>{{ trans('common.completion_date') }}</th>
<th>{{ trans('common.status')}}</th>
</tr>
</thead>
<tbody>
#foreach($projects as $project)
<tr>
<td>{!! link_to_route('project.edit', $project->name, [$project->id] )!!}</td>
<td>{{ $project->id }}</td>
<td>{{ $project->completion_date }}</td>
#if (($project->completed) == 1)
<td><span class="label label-success">{{ trans('common.completed') }}</span></td>
#elseif(($project->completion_date) < $currenttime )
<td><span class="label label-danger">{{ trans('common.toolate') }}</span></td>
#elseif(($project->active) == 0)
<td><span class="label label-default">{{ trans('common.inactive') }}</span></td>
#else
<td><span class="label label-warning">{{ trans('common.inprogress') }}</span></td>
#endif
</tr>
#endforeach
</tbody>
</table>
#endif
You have to provide the method name that defines the relationship.I mean users not user
public function index(Project $project)
{
$projects = $project->with('users')->get();
$currenttime = Carbon::now();
// return view('project.index', array('projects' => $projects, 'currenttime' => $currenttime));
return view('user.index', compact('projects'));
}

Categories