Laravel how to download txt file from database - laravel

I am working on laravel mini project, I have couple small issues, but this one is pretty tricky, I checked all possible solution, nothing worked.
When I click on download, downloading process starts, but then I got message in Failed - Server Problem.
I would like download file named in format name-last_name.txt, incase there are two people with the same name name-last_name/2.txt
If you can share with me any knowledge is the correct process of it, I will appreciate a lot
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Storage;
use App\Client;
class FormsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$clients = Client::all();
return view('/index')->with('clients', $clients);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view ('create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$this->validate($request, [
'name' => 'required',
'last_name' => 'required',
'phone'=> 'required',
'agree'=> 'required'
]);
$client = new Client;
$client->name = $request->input('name');
$client->last_name = $request->input('last_name');
$client->phone = $request->input('phone');
$client->call_time = $request->input('call_time');
$client->agree = $request->input('agree');
$client->save();
return redirect('/')->with('success', 'Klient vytvořen');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
$client = Client::find($id);
return view ('show')->with('client', $client);
}
public function download(){
$client = Client::find($id);
return response()->download($pathToFile);
}
}
Blade File is
#extends('layout')
#section('content')
<div class="row">
<div class="col-9 mt-5">
<h1>Seznam klientů</h1>
</div>
<div class="col-3 mt-5">
<h6>Nový klient</h6>
</div>
</div>
<div class="container">
#if(count($clients)>0)
<ul class="list-group">
<table class="table">
#foreach($clients as $client)
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Jméno</th>
<th scope="col">Příjmení</th>
<th scope="col">Telefonní číslo</th>
<th scope="col">Provolaný čas</th>
<th scope="col">Souhlas</th>
<th scope="col">Stahnout data</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"> </th>
<td>{{$client->name}}</td>
<td>{{$client->last_name}}</td>
<td>{{$client->phone}}</td>
<td>{{$client->call_time}}</td>
<td>{{$client->agree}}</td>
<td><a href="download/{{$client->name}}"
download="{{$client->name}}">
<button type="button" class="btn btn-
primary">
Download
</button>
</a></td>
</tr>
</tbody>
</table>
#endforeach
</ul>
#else
<p>Seznam je prázdny</p>
#endif
</div>
#endsection
Route
Route::resource('/', 'FormsController');
Route::get('/{$id}', 'FormsController#download');

Related

How to implement a simple search function for laravel CRUD

When I click the search button, this shows.
error image
It shows Error Exception for (Cannot use object of type Illuminate\Database\MySqlConnection as array )
<div class='container'>
<div class="row" >
<div class="col-md-12">
<br />
<h3 align="center">Data Pesakit</h3>
<br />
#if($message = Session::get('success'))
<div class="alert alert-success">
<p>{{$message}}</p>
</div>
#endif
<div align="right">
Add
<br />
<br />
</div>
<div class="col-md-12">
<form action="/search" method="get" class="d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0">
<div class="form-group">
<input class="form-control" type="search" name="search" />
<span class="form-group-btn">
<button class="btn btn-primary" type="submit">Search</button>
</span>
</div>
</form>
</div>
<table class="table table-bordered">
<tr>
<th>Nama Pertama</th>
<th>Nama Akhir</th>
<th>Kad Pengenalan</th>
<th>No Telefon</th>
<th>Alamat Rumah</th>
<th>Alamat Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach($pesakit as $row)
<tr>
<td>{{$row['namaPertama']}}</td>
<td>{{$row['namaAkhir']}}</td>
<td>{{$row['kadPengenalan']}}</td>
<td>{{$row['noTelefon']}}</td>
<td>{{$row['alamatRumah']}}</td>
<td>{{$row['email']}}</td>
<td>Edit</td>
<td><form method="post" class="delete_form" action="{{action('PesakitController#destroy',$row['id'])}}">
{{csrf_field()}}
<input type="hidden" name="_method" value="DELETE" />
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('.delete_form').on('submit', function(){
if(confirm("Are you sure you want to delete it?"))
{
return true;
}
else
{
return false;
}
});
});
</script>
#endsection
This is code for views
class PesakitController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$pesakit = Pesakit::all()->toArray();
return view('pesakit.index', compact('pesakit'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('pesakit.create');
}
public function search(Request $request)
{
$search = $request->get('search');
$pesakit = DB::table('pesakit')
->where('namaPertama', 'like', '%'.$search. '%');
return view('pesakit.index', ['pesakit'=>$pesakit]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'namaPertama' => 'required',
'namaAkhir' => 'required',
'kadPengenalan' => 'required',
'noTelefon' => 'required',
'alamatRumah' => 'required',
'email' => 'required'
]);
$pesakit = new Pesakit([
'namaPertama' => $request->get('namaPertama'),
'namaAkhir' => $request->get('namaAkhir'),
'kadPengenalan' => $request->get('kadPengenalan'),
'noTelefon' => $request->get('noTelefon'),
'alamatRumah' => $request->get('alamatRumah'),
'email' => $request->get('email')
]);
$pesakit->save();
return redirect()->route('pesakit.create')->with('success',
'Data Berjaya Disimpan');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$pesakit = Pesakit::find($id);
return view('pesakit.edit', compact('pesakit', 'id'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'noTelefon' => 'required',
'alamatRumah' => 'required'
]);
$pesakit = Pesakit::find($id);
$pesakit->noTelefon = $request->get('noTelefon');
$pesakit->alamatRumah = $request->get('alamatRumah');
$pesakit->save();
return redirect()->route('pesakit.index')->with('success', 'Data Dikemas kini');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$pesakit = Pesakit::find($id);
$pesakit->delete();
return redirect()->route('pesakit.index')->with('success', 'Data Deleted');
}
}
This is the controller
Route::get('/', function () {
return view('utama');
});
Route::resource('pesakit', 'PesakitController');
Route::resource('petugas', 'PetugasController');
Route::resource('pendaftaran', 'PendaftaranController');
Route::get('/search','PesakitController#search');
This is the Route
I try to look for simple error such as ; or misspell or something but i cannot find it. It says some array problem but does not all crud is array??
add get()
public function search(Request $request)
{
$search = $request->get('search');
$pesakit = DB::table('pesakit')
->where('namaPertama', 'like', '%'.$search. '%')->get();
return view('pesakit.index', ['pesakit'=>$pesakit]);
}

how display the data of stock with the help of user table

I stored the User id in Stock table from session user with each row of data. Now i try to retrive the data for particlar user that's loggin at the time. Only which data show in table which row match the user_id with auth user_id.
THis is my index page
#extends('layouts.app')
#section('content')
#if($message = Session::get('success'))
<div class="alert alert-success">
<p>{{$message}}</p>
</div>
#endif
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title"> Stock
<div align="right">
Add
</div></h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead class=" text-primary">
<th>Product Name</th>
<th>Product code</th>
<th>deatils</th>
<th>Price</th>
<th>Cost</th>
<th>Quantity</th>
<th></th>
</thead>
<tbody>
#foreach($stocks as $row Auth::user()->user_id == user_if)
<tr>
<td>{{$row['product_name']}}</td>
<td>{{$row['product_code']}}</td>
<td>{{$row['details']}}</td>
<td>{{$row['price']}}</td>
<td>{{$row['cost']}}</td>
<td>{{$row['quntity']}}</td>
<td ></i>
</td>
<td>
<form id="my_form" method="post" class="delete_form" action="{{action('StockController#destroy', $row['id'])}}">
{{csrf_field()}}
<input type="hidden" name="_method" value="DELETE" />
<i class="fa fa-trash"></i>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
THis is my controller file which i try to display data of particular user which is loggin at the time
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Stock;
use Auth;
class StockController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$stocks = Stock::all()->toArray();
return view('stock.index', compact('stocks'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('stock.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'user_id' =>'required',
'product_name' => 'required',
'product_code' => 'required',
'details' => 'required',
'price' => 'required',
'cost' => 'required',
'quntity' => 'required'
]);
$stock = new Stock([
'user_id' => $request->get('user_id'),
'product_name' => $request->get('product_name'),
'product_code' => $request->get('product_code'),
'details' => $request->get('details'),
'price' => $request->get('price'),
'cost' => $request->get('cost'),
'quntity' => $request->get('quntity')
]);
$stock->save();
return redirect()->route('stock.index')->with('success', 'Data Added');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$stock = Stock::find($id);
return view('stock.edit', compact('stock', 'id'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'product_name' => 'required',
'product_code' => 'required',
'details' => 'required',
'price' => 'required',
'cost' => 'required',
'quntity' => 'required'
]);
$stock = Stock::find($id);
$stock->product_name = $request->get('product_name');
$stock->product_code = $request->get('product_code');
$stock->details = $request->get('details');
$stock->price = $request->get('price');
$stock->cost = $request->get('cost');
$stock->quntity = $request->get('quntity');
$stock->save();
return redirect()->route('stock.index')->with('success', 'Data Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$stock = Stock::find($id);
$stock->delete();
return redirect()->route('stock.index')->with('success', 'Data Deleted');
}
}
there are 2 ways. first is like #Keepon said: create a relationship between the user and the stock table
2:
$user = Auth::user();
$stocks = Stock::where('user_id','=',$user->id)->get();
Please change you index function
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$stocks = Stock::where('user_id', Auth::id())->get();
return view('stock.index', compact('stocks'));
}
And than in your blade
#foreach($stocks as $stock)
<tr>
<td>{{$stock->product_name}}</td>
<td>{{$stock->product_code}}</td>
<td>{{$stock->details}}</td>
<td>{{$stock->price}}</td>
<td>{{$stock->cost}}</td>
<td>{{$stock->quntity}}</td>
<td ></i>
</td>
<td>
<form id="my_form" method="post" class="delete_form" action="{{action('StockController#destroy', $stock->id)}}">
{{csrf_field()}}
<input type="hidden" name="_method" value="DELETE" />
<i class="fa fa-trash"></i>
</form>
</td>
</tr>
#endforeach
The best practice is to make a MODEL RELATIONSHIP.
To make a user and stocks relationship you need to determine what relationship would you build.
In this case I will build a relationship base on what I under stand a One To Many relationship
DATABASE
Stocks Migration
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
...
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
It should be look like the above code.
Then in your model you can connect the relationship of user and stocks
MODEL
User Model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function stocks() {
return $this->hasMany(Stock::class);
}
}
Stock Model
class Stock extends Model
{
protected $guarded = [];
public function user() {
return $this->belongsTo(User::class);
}
}
Then you can query on your controller the user stocks.
CONTROLLER
Stocks Controller
public function index() {
$stocks = auth()->user()->stocks;
return view('index', compact('stocks'));
}
If you want more example of eloquent relationship you can check this tutorial by Victor
add this function in User Model
public function stocks() {
return $this->hasMany(Stock::class);
}
in Stocks Controller
public function index()
{
$stocks = auth()->user()->stocks;
return view('stock.index', compact('stocks'));
}
in index.blade.php
#foreach($stocks as $row)
<tr>
<td>{{$row['product_name']}}</td>
<td>{{$row['product_code']}}</td>
<td>{{$row['details']}}</td>
<td>{{$row['price']}}</td>
<td>{{$row['cost']}}</td>
<td>{{$row['quntity']}}</td>
<td ></i>
</td>
<td>
<form id="my_form" method="post" class="delete_form" action="{{action('StockController#destroy', $row['id'])}}">
{{csrf_field()}}
<input type="hidden" name="_method" value="DELETE" />
<i class="fa fa-trash"></i>
</form>
</td>
#endforeach

My index suddenly having "Trying to get property of non-object" after doing edit and create blade

Thank you guys for helping me last time. the problem I am having right now is regarding with my view blade. This index.blade is completely working before I create the, edit and create blade. After I completed the the other two blade, I noticed the index.blade are now having Trying to get property of non-object
what I'm trying to do is to display category in products table.
Product Table
id , name, categories_id
Categories Table
id, name
Products Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Products extends Model
{
use SoftDeletes;
protected $fillable = [
'product_code',
'name',
'categories_id',
'wh1_limit_warning',
'wh2_limit_warning',
'price',
'selling_price',
'user_id'
];
protected $dates = ['deleted_at'];
public function category() {
// return $this->belongsTo(Categories::class);
return $this->belongsTo('App\Categories', 'categories_id', 'id');
}
}
Categories Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Categories extends Model
{
protected $fillable = ['name'];
public function Products()
{
// return $this->hasMany(Products::class);
return $this->hasMany('App\Products', 'categories_id');
}
}
Index Blade
<div class="panel-body">
<div class="result-set">
<table class="table table-bordered table-striped table-hover text-center" id="data-table">
<thead>
<tr>
<th class="col-md-1 text-center">Code</th>
<th class="col-md-2 text-center">Name</th>
<th class="col-md-2 text-center">Category</th>
<th class="col-md-1 text-center"><small>Warehouse 1<br/>Limit Warning</small></th>
<th class="col-md-1 text-center"><small>Warehouse 2<br/>Limit Warning<small></th>
<th class="col-md-1 text-center">Price</th>
<th class="col-md-1 text-center">Selling Price</th>
#can('update_product', 'delete_product')
<th class="text-center col-md-1 text-center">Actions</th>
#endcan
</tr>
</thead>
<tbody>
#foreach($products as $product)
<tr>
<td>{{ $product->product_code }}</td>
<td>{{ $product->name }}</td>
<td><b>{{ $product->category->name }}</b></td>
<td>{{ $product->wh1_limit_warning }}</td>
<td>{{ $product->wh2_limit_warning }}</td>
<td>{{ $product->price }}</td>
<td>{{ $product->selling_price }}</td>
#can('update_product')
<td>
<button data-toggle="tooltip" title="Update product" onclick="window.location='{{ route('products.edit', $product) }}'" name="edit" class="action-button edit">
<i class="fas fa-edit"></i>
</button>
<form action="{{ route('products.delete', $product )}}" method="post">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button data-toggle="tooltip" title="Delete product" type="submit" class="action-button delete" onclick="return confirm('Are you sure you want to delete this?');"><i class="fas fa-trash-alt"></i></button>
</form>
</td>
#endcan
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
Products Controller
<?php
namespace App\Http\Controllers;
use App\Products;
use App\Categories;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = Products::with('category')->get();
return view('products.index')->with('products',$products);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$products = Products::with('category')->get();
$categories = Categories::get()->pluck('name','id');
return view('products.create',compact('categories'))->with('products', $products);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$products = Products::create($request->only(
'product_code',
'name',
'categories_id',
'wh1_limit_warning',
'wh2_limit_warning',
'price',
'selling_price',
'user_id'
));
$this->validate($request, [
'product_code' => '',
'name' => '',
'categories_id' => 'required|integer',
'wh1_limit_warning' => 'required|integer',
'wh2_limit_warning' => 'required|integer',
'price' => 'required|integer',
'selling_price' => 'required|integer',
'user_id' => 'required|integer',
]);
flash('New product added!');
return redirect(route('products.index'));
}
/**
* Display the specified resource.
*
* #param \App\Products $products
* #return \Illuminate\Http\Response
*/
public function show(Products $products)
{
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Products $products
* #return \Illuminate\Http\Response
*/
public function edit(Products $product)
{
$products = Products::all();
$categories = Categories::all('name','id');
return view('products.edit',compact('product','categories'));
//return view('products.edit',compact('product','categories'))->with('products', $products);
// return view('products.edit', compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Products $products
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Products $product)
{
$product->update($request->only(
'product_code',
'name',
'categories_id',
'wh1_limit_warning',
'wh2_limit_warning',
'price',
'selling_price',
'user_id'
));
return redirect()->route('products.index');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Products $products
* #return \Illuminate\Http\Response
*/
public function destroy(Products $product)
{
$product->delete();
return redirect(route('products.index'));
}
}
I can't see where did I go wrong because I did not change anything in public function index() of my controller. Again, EDIT and Create is workingI was able to display the categories in dropdown with no any issue only this index.blade.
Please see this screenshot of the issue
Thank you so much in advance!
My guess is that your query returns an array instead of an object. Try dumping your return to make sure.
If it is an array, you can try using [] instead of -> in your index.blade.php:
<td><b>{{ $product->category['name'] }}</b></td>
Seems there will be some product which don't have any category. So that product wont be linked with any category and it won't have any category object that's why it is giving this error.
You can add a check before displaying the category name that product contains category or not.
<td><b>{{ $product->category ? $product->category->name : "" }}</b></td>

use multiple for loops in a td element in laravel

Hello guys i have 3 eloquent tables members, pledge and campaign and they are have a relationship amongst each other namely:
for member model
protected $table = "members";
public function loans()
{
return $this->hasMany(Loan::class, 'borrower_id', 'id');
}
public function user()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function pledges()
{
return $this->hasMany(Pledge::class, 'member_id', 'id');
}
for campaign
protected $table = "campaigns";
public function pledges()
{
return $this->hasMany(Pledge::class, 'campaign_id', 'id')->orderBy('created_at', 'desc');
}
}
then for pledge model
protected $table = "pledges";
public function campaign()
{
return $this->hasOne(Campaign::class, 'id', 'campaign_id');
}
public function member()
{
return $this->hasOne(Member::class, 'id', 'member_id');
}
}
IN the plegde.create.blade
<div class="control-group">
<label class="control-label">Member</label>
<div class="controls">
<select>
#foreach ($member as $members)
<option>{{ $members->first_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Campaign</label>
<div class="controls">
<select>
#foreach ($campaign as $campaigns)
<option>{{ $campaigns->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Amount</label>
<div class="controls">
<input type="number" name="amount" id="required" value="{{ old('amount') }}">
#if ($errors->has('amount'))
<p class="alert alert-danger">{{ $errors->first('amount') }}
#endif
</div>
</div>
<div class="control-group">
<label class="control-label">Date (mm-dd)</label>
<div class="controls">
<div data-date="2012-11-02" class="input-append date datepicker">
<input type="text" name="date" value="2012-11-02" data-date-format="yyyy-mm-dd" class="span11" value="{{ old('date') }}">
#if ($errors->has('date'))
<p class="alert alert-danger">{{ $errors->first('date') }}
#endif
<span class="add-on"><i class="icon-th"></i></span> </div>
</div>
</div>
<div class="control-group">
<label class="control-label">Description</label>
<div class="controls">
<input type="text" name="notes" id="required" value="{{ old('notes') }}">
#if ($errors->has('notes'))
<p class="alert alert-danger">{{ $errors->first('notes') }}
#endif
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-success">
</div>
</form>
then in my pledge.index.blade.php i have this but it is not showing proerly this is the code
<div class="widget-content nopadding">
<table class="table table-bordered data-table">
<thead>
<tr>
<th>#ID</th>
<th>Campaign</th>
<th>Member</th>
<th>Amount</th>
<th>Date</th>
<th>Notes</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="gradeX">
#foreach ($member as $members)
<td>{{ $members->first_name }}</td>
#endforeach
#foreach ($campaign as $campaigns)
<td>{{ $campaigns->name }}</td>
#endforeach
#foreach ($pledge as $pledges)
<td>{{ $pledges->amount }}</td>
#endforeach
#foreach ($pledge as $pledges)
<td>{{ $pledges->date }}</td>
#endforeach
</tr>
</tbody>
</table>
</div>
Any help would be appreciated.
These are the controllers
Campaign Controller
use App\Campaign;
use Illuminate\Http\Request;
class CampaignController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$campaign = Campaign::all();
return view('campaign.index', compact('campaign'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('campaign.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name'=>'required',
'goal'=> 'required',
]);
// return $request->all();
$campaign = new Campaign;
$campaign->name = $request->name;
$campaign->goal = $request->goal;
$campaign->notes= $request->notes;
$campaign->save();
return redirect (route('campaign.index'));
}
PLedge Controller
use App\Campaign;
use App\Member;
use App\Pledge;
use Illuminate\Http\Request;
class Pledgecontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$member= Member::all();
$campaign= Campaign::all();
$pledge= Pledge::all();
return view ('pledges.index', compact ('member', 'campaign', 'pledge'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$member= Member::all();
$campaign= Campaign::all();
$pledge= Pledge::all();
return view ('pledges.create', compact ('member', 'campaign', 'pledge'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$pledge= new Pledge;
$pledge->member_id = $request->member_id;
$pledge->campaign_id = $request->campaign_id;
$pledge->amount = $request->amount;
$pledge->date = $request->date;
$pledge->notes = $request->notes;
$pledge->save();
return redirect (route('pledge.index'));
// return $request->all();
}
Member Controller
use App\Member;
use Illuminate\Http\Request;
class MemberController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$member = Member::all();
return view('member.index', compact('member'));
// return view ('member.data');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view ('member.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'first_name'=> 'required',
'middle_name'=>'required',
'last_name'=>'required',
'gender'=> 'required',
'marital_status'=> 'required',
'status'=> 'required',
'mobile_phone'=> 'required',
'address'=> 'required',
'email'=> 'required',
'dob'=> 'required',
'photo'=> 'required | image|mimes:jpeg,png,jpg,gif,svg|max:700',
]);
if ($request->hasFile('photo')) {
// $request->photo->store('public');
$imageName= $request->photo->store('public');
}
$member = new Member;
$member->first_name = $request->first_name;
$member->middle_name = $request->middle_name;
// $member->photo = $request->photo;
$member->photo = $imageName;
$member->last_name = $request->last_name;
$member->gender = $request->gender;
$member->marital_status = $request->marital_status;
$member->status = $request->status;
$member->mobile_phone = $request->mobile_phone;
$member->address = $request->address;
$member->email = $request->email;
$member->dob = $request->dob;
$member->save();
return redirect (route('member.index'));
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$member = Member::where('id', $id)->get();
return view ('member.edit', compact('member'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'first_name'=> 'required',
'middle_name'=>'required',
'last_name'=>'required',
'gender'=> 'required',
'marital_status'=> 'required',
'status'=> 'required',
'mobile_phone'=> 'required',
'address'=> 'required',
'email'=> 'required',
'dob'=> 'required',
'photo'=> 'required | image|mimes:jpeg,png,jpg,gif,svg|max:700',
]);
if ($request->hasFile('photo')) {
// $request->photo->store('public');
$imageName= $request->photo->store('public');
}
$member = Member::find($id);
$member->first_name = $request->first_name;
$member->middle_name = $request->middle_name;
// $member->photo = $request->photo;
$member->photo = $imageName;
$member->last_name = $request->last_name;
$member->gender = $request->gender;
$member->marital_status = $request->marital_status;
$member->status = $request->status;
$member->mobile_phone = $request->mobile_phone;
$member->address = $request->address;
$member->email = $request->email;
$member->dob = $request->dob;
$member->save();
return redirect (route('member.index'));
// return $request->all();
}
This is not a good solution. Same table, different models, different foreachs.
You can make just one foreach and function. Like this:
public function memberFunction()
{
return $this->hasOne('App\Member');
}
//
public function campaignFunction()
{
return $this->hasOne('App\Campaign');
}
We made the connection as a function. Now inside the foreach use the function with [' '] tags.
#foreach ($example as $examples)
<td>{{ $examples->memberFunction['firstname'] }}</td>
<td> {{ $examples->campaignFunction['name'] }} </td>
#endforeach
you can continue like this.

Laravel view won't loop model even though it is populated

I'm creating a web based interface for my dovecot database.
I can get a list of all the virtual domains in the database and the number of emails and aliases easily enough.
But when I try to load a page to list the emails under a specific domain, it goes weird.
Three simple models:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class VirtualDomain extends Model
{
public function emails()
{
return $this->hasMany('App\VirtualUser', 'domain_id');
}
public function aliases()
{
return $this->hasMany('App\VirtualAlias', 'domain_id');
}
}
class VirtualUser extends Model
{
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
];
}
class VirtualAlias extends Model
{
//
}
My default controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\VirtualDomain;
use App\VirtualUser;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('home', [
'domains' => VirtualDomain::all(),
]);
}
public function domain($name)
{
$domain = VirtualDomain::where('name', $name)->first();
return view('domain', [
'domain' => $domain,
'emails' => VirtualUser::where('domain_id', $domain->id),
]);
}
}
and a couple of simple blades
home.blade.php
<p>
{{ $domains->count() }} domains
</p>
<table class="table-summary">
<thead>
<tr>
<th>name</th>
<th>emails</th>
<th>aliases</th>
<th class="table-summary-options">options</th>
</tr>
</thead>
<tbody>
#foreach ($domains as $domain)
<tr>
<td><a title="view emails for this domain" href="domain/{{ $domain->name }}">{{ $domain->name }}</a></td>
<td>{{ $domain->emails->count() }}</td>
<td>{{ $domain->aliases->count() }}</td>
<td class="table-summary-options"><a class="ui-action" title="remove this domain" href=""><img src="/img/ui/remove.png" alt="remove"></a></td>
</tr>
#endforeach
</tbody>
</table>
and domain.blade.php
<p>
<< - {{ $domain->name }} - {{ $emails->count() }} emails
</p>
<table class="table-summary">
<thead>
<tr>
<th>email</th>
<th class="table-summary-options">options</th>
</tr>
</thead>
<tbody>
#foreach ($emails as $email)
<tr>
<td><a title="view aliases for this domain" href="email/{{ $email->email }}">{{ $email->email }}</a></td>
<td class="table-summary-options"><a class="ui-action" title="remove this email" href=""><img src="/img/ui/remove.png" alt="remove"></a></td>
</tr>
#endforeach
</tbody>
</table>
The view outputs the correct number of emails under the domain with {{ $emails->count() }} - but the#foreach ($emails as $email)` does not loop.
When I modify the blade to simple use the emails from the domain variable ({{ $domain->emails->count() }} and #foreach ($domain->emails as $email)), I get the right count and the list is populated correctly.
What's making it go wrong when using the emails variable?
You have to make a small change for it to work
public function domain($name)
{
$domain = VirtualDomain::where('name', $name)->first();
return view('domain', [
'domain' => $domain,
'emails' => VirtualUser::where('domain_id', $domain->id)->get(),
]);
}
Without ->get() you will get a query builder instance while with get() will return a collection. In the foreach loop a collection can be iterated while a query builder instance can't be.
Hope this helps

Resources