I try to give the data from database to the blade.php.
The controller:
class DataController extends Controller
{
// sql query from datebase
public function question_number()
{
$questions = DB::table('questions')->sum('id');
return view('/statistics',['question' => $questions ]);
}
public function group_number()
{
$groups = DB::table('groups')->sum('id');
return view('/statistics', ['group' => $groups ]);
}
}
in there I have define the value $question and $group
and in Blade.php I have try to use this value:
<div>Die Anzahl von Fragen</div>
<p> {{ $question }} </p>
<div>Die Anzahl von Gruppen</div>
<p> {{ $group }} </p>
in route
Route::get('/statistics', 'DataController#question_number');
Route::get('/statistics', 'DataController#group_number');
but the error is always
Undefined variable $question
What did I miss? And what should I do?
You want to send 2 variables to one view, I think. To do this you don't need 2 routes and 2 controllers. In fact you CAN'T do that.
Route File:
Route::get('/statistics', 'DataController#question_number');
Controller:
class DataController extends Controller
{
// sql query from datebase
public function question_number()
{
$questions = DB::table('questions')->sum('id');
$groups = DB::table('groups')->sum('id');
return view('/statistics',['question' => $questions , 'group' => $groups]);
}
}
View (without change):
<div>Die Anzahl von Fragen</div>
<p> {{ $question }} </p>
<div>Die Anzahl von Gruppen</div>
<p> {{ $group }} </p>
Related
In laravel controller I have following code:
public function getAdmins(){
//$users = $this->user->all();
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
$exceptSuperadmin = array();
foreach($users as $user){
if(!$user->isUser())
$staffs[] = $user;
}
$users = #$staffs;
return view('users::admins.list')->with('staffs',$users)->with('search',$search);
}
In Model I have:
public function findUsers($search)
{
return self::where('name','like','%'.$search['name'].'%')
->where('username','like','%'.$search['uname'].'%')
->where('role','like','%'.$search['role'].'%')
->paginate(5);
}
And In blade file I have:
#if($staffs)
#foreach($staffs as $staff)
<!-- Some code here to loop array -->
#endforeach
#else
No Staffs
#endif
{!! $staffs->render() !!} Error comes at this line
I am not geeting why this error comes....staffs is an array and render() a function to echo the pagination pages...but can't getting the error...Anybody to help.
By applying foreach the pager object and assign an array you lose the paging properties, so you will have an array rather than a pager object.
I recommend the following solution for your case:
Controller:
public function getAdmins(){
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
return view('users::admins.list')->with('users',$users)->with('search',$search);
}
Blade file:
#if($users)
#foreach($users as $user)
#if(!$user->isUser())
<!-- Some code here to loop array -->
#endif
#endforeach
#else
No Staffs
#endif
{!! $users->render() !!}
NO, render() doesn't work on an object per se, neither on the array you are creating out of the required object for the pagination to work (LengthAwarePaginator)
Since you have a collection, and you need one, you could use one of the methods provided to do your filtering, such as filter.
Something like (untested but should work):
$staff = $users->filter(function ($value, $key) {
return !$value->isUser();
});
I am new to Laravel and I have been trying to store all records of table 'student' to a variable and then pass that variable to a view so that I can display them.
I have a controller - ProfileController and inside that a function:
public function showstudents() {
$students = DB::table('student')->get();
return View::make("user/regprofile")->with('students',$students);
}
In my view, I have this code:
<html>
<head>
//---HTML Head Part
</head>
<body>
Hi {{ Auth::user()->fullname }}
#foreach ($students as $student)
{{ $student->name }}
#endforeach
#stop
</body>
</html>
I am receiving this error: Undefined variable: students (View:regprofile.blade.php)
Can you give this a try,
return View::make("user/regprofile", compact('students')); OR
return View::make("user/regprofile")->with(array('students'=>$students));
While, you can set multiple variables something like this,
$instructors="";
$instituitions="";
$compactData=array('students', 'instructors', 'instituitions');
$data=array('students'=>$students, 'instructors'=>$instructors, 'instituitions'=>$instituitions);
return View::make("user/regprofile", compact($compactData));
return View::make("user/regprofile")->with($data);
For Passing a single variable to view.
Inside Your controller create a method like:
function sleep()
{
return view('welcome')->with('title','My App');
}
In Your route
Route::get('/sleep', 'TestController#sleep');
In Your View Welcome.blade.php. You can echo your variable like {{ $title }}
For An Array(multiple values) change,sleep method to :
function sleep()
{
$data = array(
'title'=>'My App',
'Description'=>'This is New Application',
'author'=>'foo'
);
return view('welcome')->with($data);
}
You can access you variable like {{ $author }}.
The best and easy way to pass single or multiple variables to view from controller is to use compact() method.
For passing single variable to view,
return view("user/regprofile",compact('students'));
For passing multiple variable to view,
return view("user/regprofile",compact('students','teachers','others'));
And in view, you can easily loop through the variable,
#foreach($students as $student)
{{$student}}
#endforeach
You can try this as well:
public function showstudents(){
$students = DB::table('student')->get();
return view("user/regprofile", ['students'=>$students]);
}
Also, use this variable in your view.blade file to get students name and other columns:
{{$students['name']}}
Try with this code:
return View::make('user/regprofile', array
(
'students' => $students
)
);
Or if you want to pass more variables into view:
return View::make('user/regprofile', array
(
'students' => $students,
'variable_1' => $variable_1,
'variable_2' => $variable_2
)
);
In Laravel 5.6:
$variable = model_name::find($id);
return view('view')->with ('variable',$variable);
public function showstudents() {
$students = DB::table('student')->get();
return (View::make("user/regprofile", compact('student')));
}
try with this code :
Controller:
-----------------------------
$fromdate=date('Y-m-d',strtotime(Input::get('fromdate')));
$todate=date('Y-m-d',strtotime(Input::get('todate')));
$datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To
return view('inventoryreport/inventoryreportview', compact('datas'));
View Page :
#foreach($datas as $student)
{{$student}}
#endforeach
[Link here]
$books[] = [
'title' => 'Mytitle',
'author' => 'MyAuthor,
];
//pass data to other view
return view('myView.blade.php')->with('books');
or
return view('myView.blade.php','books');
or
return view('myView.blade.php',compact('books'));
----------------------------------------------------
//to use this on myView.blade.php
<script>
myVariable = {!! json_encode($books) !!};
console.log(myVariable);
</script>
In laravel 8 and above, You can do route binding this way.
public function showstudents() {
$students = DB::table('student')->get();
return view("user/regprofile",['students'=>$students]);
}
In the view file, you can access it like below.
#foreach($students as $student)
{{$student->name}}
#endforeach
in my application i want to simplify forms and change Form::model to use both of Update and Insert, for have this ability i'm create this route:controller to show View and modrate it:
Route::controller(
'customers' , 'customersController',
array(
'getIndex' =>'customers.index',
'postUpdate'=>'customers.update'
)
);
customersController controller class:
<?php
class customersController extends \BaseController
{
public function getIndex()
{
if ( Auth::check() ){
$customers = new Customers;
return View::make('layouts.customers')->with('customers', $customers);
}
return Redirect::route('dashboard');
}
public function postUpdate($id)
{
print_r( $id);
die;
}
}
?>
in getIndex i can return to view customers.blade.php corretcly and i can be create new variable as an new Customers, in view i'm create below form from created new instance from Customers:
{{ Form::model($customers,array('route' => array('customers.update', $customers->id))) }}
...
{{ Form::submit('UPDATE', array('class'=>'btn btn-default btn-default-small') ) }}
{{ Form::close() }}
now i want to send form values to controler, but after send i get this error:
ERROR:
Missing argument 1 for customersController::postUpdate()
form in view must be like with this code :
{{ Form::model($customers,array('route' => array('customers.update', $customers->id))) }}
and your Form::text must be like with:
{{ Form::text('name', $customers->name, array('class'=>'form-control rtl' ) ) }}
Route:
Route::controller(
'customers', 'customersController',
array(
'getIndex' => 'customers.index',
'postUpdate' => 'customers.update'
)
);
now in controller you can try this code to detect form is update or insert
public function postUpdate()
{
if (Input::get('id')) {
$customer = Customers::find(Input::get('id'));
} else {
$customer = new Customers;
}
...
...
...
}
This is the error I am getting on the sample view:
Undefined variable: sampleRecord
This is the controller code:
public function show($sample_id)
{
return View::make('samples.show')->with([
$this->sampleRepository->find($sample_id),
$this->sampleRecord->getSamplePartNumberRecord,
]);
}
This is the view code:
<p>{{ $sampleRecord }}</p>
#foreach($sampleRecord->SamplePartNumbers() as $samplePartNumberRecord)
<p>Sample Part Number: <br />{{ $samplePartNumberRecord }}</p>
#endforeach
your controller should be:
public function show($sample_id)
{
return View::make('samples.show')->with([
"sampleRepository" => $this->sampleRepository->find($sample_id),
"sampleRecord" => $this->sampleRecord->getSamplePartNumberRecord,
]);
}
Newbie to PHP/Laravel here so please be patient.
I have a webpage that is searching based on 3 criteria for dogs , breed, sex and radius.
here is the relevant code:
search page
<div class="col-md-12 zero-pad-left zero-pad-right">
{{ Form::open(array('action' => array('DogsController#index'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
<div id="prefetch">
{{ Form::text('search-breed', null, array('class' => 'typeahead form-group form-control', 'placeholder' => 'Search by breed here...')) }}
{{ Form::text('sex', null, array('class' => 'form-group form-control', 'placeholder' => 'Search by sex here...')) }}
{{ Form::text('miles', null, array('class' => 'form-group form-control', 'placeholder' => 'Search by distance here...')) }}
</div>
{{ Form::submit('Search', array('class' => 'btn btn-default search-bar-btn')) }}
{{ Form::close() }}
ControllerPage
class DogsController extends \BaseController {
public function __construct()
{
// call base controller constructor
parent::__construct();
// run auth filter before all methods on this controller except index and show
$this->beforeFilter('auth', array('except' => array('show')));
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
if (Input::has('search')) {
$queryString = Input::get('search');
$dogs = Dog::where('name', 'LIKE', "%$queryString%")->orderBy('name')->paginate(5);
}
elseif (Input::has('search-breed'))
{
$dogs = Dog::whereHas('breed', function($q)
{
$queryString = Input::get('search-breed');
$q->where('name', 'LIKE', "%$queryString%");
})->orderBy('name')->paginate(5);
} //end elseif
else {
$dogs = Dog::orderBy('name')->paginate(5);
} //end else
return View::make('dogs.index')->with(array('dogs' => $dogs));
} //end function index()
when i enter a search for poodle, male, within 20 miles, the url shows as follows:
http://ruff-love.dev/dogs?search-breed=poodle&sex=M&miles=20
The search currently works ok when searching for just breed.
I cant seem to figure out the syntax to add the SEX and RADIUS criteria also.
it should allow for those criteria to be null and still perform the query.
any advice would be greatly apprecaited
You can use query scopes http://laravel.com/docs/eloquent#query-scopes to make it verbose and easier in your controller (or wherever you will be doing it in future) then chain them according to your needs:
// Dog model
public function scopeSearchBreed($query, $breed)
{
$query->whereHas('breed', function ($q) use ($breed) {
$q->where('name', 'like', "%{$breed}%");
});
}
public function scopeWithinRadius($query, $radius)
{
$query->where(...); // do math here
}
Then all you need is this:
public function index()
{
$q = Dog::query();
if (Input::has('search'))
{
// simple where here or another scope, whatever you like
$q->where('name','like',Input::get('search'));
}
if (Input::has('search-breed'))
{
$q->searchBreed(Input::get('search-breed'));
}
if (Input::has('sex'))
{
$q->where('sex', Input::get('sex'));
}
if (Input::has('radius'))
{
$q->withinRadius(Input::get('radius'));
}
$dogs = $q->orderBy(..)->paginate(5);
// ...
Here's one possible solution, I think there are probably others. Create an empty query builder with the query() function and add the non-null clauses to it, then call the paginate() function at the end.
$builder = Dogs::query();
if (Input::has('search')) {
$queryString = Input::get('search');
$builder->where('name', 'LIKE', "%$queryString%");
}
// ... more clauses from the querystring
$dogs = $builder->orderBy('name')->paginate(5);
$builder = Dogs::query();
$term = Request::all();
if(!empty($term['breed'])){
$builder->where('breed','=',$term['breed']);
}
if(!empty($term['sex'])){
$builder->where('sex','=',$term['sex']);
}
if(!empty($term['radius'])){
$builder->where('radius','=',$term['radius']);
}
$result = $builder->orderBy('id')->get();
$area = Area::query();
if (Input::has('search')) {
$queryString = Input::get('search');
$area->where('name', 'LIKE', "%" . $queryString . "%");
}
$result = $area->orderBy('name')->paginate(5);