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'));
}
Related
This is how my app generate a report (excel file) from my app:
Export/ActividadesporTodosServiciosExport.php
public function collection()
{
return Actividad::whereMonth('fecha_inicio', '12')
->whereYear('fecha_inicio', '2022')
->orderBy('servicio_id', 'ASC')
->with('servicio')
->get();
}
public function headings(): array
{
return [
'SERVICIO',
'DESCRIPCION',
];
}
public function map($actividad) : array
{
$nombre = [];
$descripcion = [];
foreach($actividad as $activity){
// dump($actividad);
$nombre[]=$actividad->descripcion;
foreach($actividad->servicio as $key => $servicio){
$descripcion = $actividad->servicio->nombre;
}
}
return [
[
$nombre[0],
$descripcion,
'',
'',
],
];
}
The screenshot shows 4 records in 4 rows, and I wanna try to convert that 4 records in one only cell of a row, like this example:
You could do that easily in a view.
https://docs.laravel-excel.com/3.1/exports/from-view.html
namespace App\Exports;
use App\Models\Actividad;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
class ActividadesporTodosServiciosExport implements FromView
{
public function view(): View
{
$actividades = Actividad::query()
->whereMonth('fecha_inicio', '12')
->whereYear('fecha_inicio', '2022')
->orderBy('servicio_id', 'ASC')
->with('servicio')
->get();
return view('exports.your_view', [
'actividades' => $actividades,
]);
}
}
resources/views/exports/your_view.blade.php
<table>
<thead>
<tr>
<th>SERVICIO</th>
<th>DESCRIPCION</th>
</tr>
</thead>
<tbody>
#foreach($actividades as $actividad)
<tr>
<td>{{ $actividad->descripcion }}</td>
<td>{{ $actividad->servicio->implode('nombre', "\n") }}</td>
</tr>
#endforeach
</tbody>
</table>
Alternatively using the rowspan attribute to get grouped cells in the spreadsheet
<table>
<thead>
<tr>
<th>SERVICIO</th>
<th>DESCRIPCION</th>
</tr>
</thead>
<tbody>
#foreach($actividades as $actividad)
<tr>
<td rowspan="{{ $actividad->servicio->count() + 1">{{ $actividad->descripcion }}</td>
</tr>
#foreach($actividad->servicio as $servicio)
<tr>
<td>{{ $servicio->nombre }}</td>
</tr>
#endforeach
#endforeach
</tbody>
</table>
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.
}
hellow i want to show 10 persons who has deposited amount in last24 hours . i am able to show there user_id and amount but i want users name instead of user_id.
i have no name colum in $funds it is in users
i have this code:
<div class="col-md-6">
<div class="text-center"><h4 class="text-success">Last 10 Investors</h4></div>
<table class="table text-white" >
<tbody>
#foreach( \App\Fund::where('created_at', '>', \Carbon\Carbon::now()->subHours(24))->orderBy('id', 'DESC')->take(10)->get() as $fund)
<tr>
<th scope="row"></th>
<td>{{ $fund->user_id }}</td>
<td class="text-center text-warning">{{ $fund->total }}</td>
<td class="text-right"><img src="https://adsok.com/img/btc.png" alt="Bitcoin"> <i><b>bitcoin</b></i><br></td><br>
</tr>#endforeach
</tbody>
</table>
</div>
Set up a relation from your Fund Model to the User Model
In your Fund model,
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
and you could access the User that belongs to the fund as
$fund->user->{your-username-field}
OR if you don't want to set up a relationship and fetch the username, you could do so by
$user = \App\User::find($fund->user_id);
if (! empty($user)) {
$user_name = $user->user_name; // or whatever the username field is
}
Try like this :
#foreach( \App\Fund::select("*")->with('users')->where('created_at', '>', \Carbon\Carbon::now()->subHours(24))->orderBy('id', 'DESC')->take(10)->get()->toArray() as $fund)
<tr>
<th scope="row"></th>
<td>{{ $fund['user']['user_name'] }}</td>
<td class="text-center text-warning">{{ $fund->total }}</td>
<td class="text-right"><img src="https://adsok.com/img/btc.png" alt="Bitcoin"> <i><b>bitcoin</b></i><br></td><br>
</tr>#endforeach
so you have to models: "Fund" and "User".
you should connect them with Laravel's Relationships:
add this method to "User" model:
public function funds()
{
return $this->hasMany('App\Fund', 'user_id');
}
then in "Fund" model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
now you can access user's name from funds:
i suggest you to retrive your datas in controller, not views:
public function index()
{
$funds = Fund::with('user')->
where('created_at', '>', \Carbon\Carbon::now()->
subHours(24))->orderBy('id', 'DESC')->take(10)->get();
return view('viewName', ['funds' => $funds]);
}
then in view:
#foreach ($funds as $fund)
{{ $fund->user->name }}
#endforeach
I am having trouble with my code. I have two tables Stocks and StockLists however, I want to get all the related stock in the stocks list based on the stock code. But the result is repeated in each stocks....
Here is the link of the image https://www.screencast.com/t/rHdT2gigh
public function index()
{
$stocks = Stock::all();
foreach ($stocks as $stock) {
$stockInfos = DB::table('stocksList')
->where('stockCode', $stock->stockCode)
->take(3)
->get();
}
return view('welcome', compact('stocks', 'stockInfos'));
}
Here is my blade.php
#forelse($stocks as $stock)
<tr align="left">
<th scope="row">{{ $stock->stockCode }}</th>
<td><strong>{{ $stock->stockName }}</strong></td>
<td><strong>
#forelse($stockInfos as $stockInfo)
{{ $stockInfo->stockDate }} : {{ $stockInfo->stockPrice }}
<br>
#empty
<em>No Data</em>
#endforelse
</strong></td>
</tr>
#empty
#endforelse
You are overwritting the $stockInfos variable try with
public function index()
{
$stocks = Stock::all();
$stockInfos = [];
foreach ($stocks as $stock) {
array_push($stockInfos,DB::table('stocksList')
->where('stockCode', $stock->stockCode)
->take(3)
->get());
}
return view('welcome', compact('stocks'))->with('stockInfos',collect($stockInfos));
}
And in your view :
#forelse($stocks as $stock)
<tr align="left">
<th scope="row">{{ $stock->stockCode }}</th>
<td><strong>{{ $stock->stockName }}</strong></td>
<td><strong>
#forelse($stockInfos->where('stockCode',$stock->stockCode) as $stockInfo)
{{ $stockInfo->stockDate }} : {{ $stockInfo->stockPrice }}
<br>
#empty
<em>No Data</em>
#endforelse
</strong></td>
</tr>
#empty
#endforelse
Try this :
$stockInfos = DB::table('Stock')
->join('stocksList','stocksList.stockCode','=','Stock.stockCode')
->get();
I am retrieving all Tickets assigned to a user. A single ticket has a foreign key to users table. These are the code below:
App\Models\User.php
protected $appends = ['full_name', 'avatar'];
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
App\Http\Controllers\TicketsController.php
/**
* Display a listing of the resource.
*/
public function index()
{
$tickets = Ticket::paginate(25);
$users = User::all();
//return view('user.tickets.index', compact('tickets'));
return View::make('user.tickets.index', compact('tickets','users'));
}
Resources/Views/User/Tickets/index.blade.php
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Status</th>
<th>Assigned To</th>
</tr>
</thead>
<tbody>
#foreach($tickets as $item)
<tr>
<td>{{ $item->status }}</td>
<td>{{ $item->user_id }}</td>
</tr>
#endforeach
</tbody>
</table>
I want to convert the field {{ $item->user_id }} into {{ $item->first_name where id = $item->user_id }} The field should be converted into the First Name according to the $item->user_id
user_id is a foreign key to tickets and the equivalent of it is the is of Users table.
Please help.
Firstly it's not good practice to write db query in views. You can accomplish that by defining a relation in your Ticket model class.
public function user()
{
return $this->belongsTo(User::class);
}
Now you can access user name by $item->user->first_name.
Try this:
#foreach (DB::table('table_name')->where('id', '=', $tickets->id)->get() as $id)
{{ $id->id }}
{{ $item->column_val1}}
{{ $item->column_val2}}
{{ $item->column_val3}}
#endforeach