How can I pass value from blade into controller in Laravel? [duplicate] - php

Im passing data to my blade view with return View::make('blog', $posts); and in my blade view I'm trying to run an #foreach ($posts as $post) I end up with an error saying that $posts isn't defined.
My question is how would the $posts array be called?

You can pass data to the view using the with method.
return View::make('blog')->with('posts', $posts);

As of Laravel 5, the View::make() facade method from the 2013 accepted answer has been deprecated. Passing data to the view is now done using the view() helper function like this:
return view("blog", ["posts"=>$posts]);
Or, the same thing:
return view("blog", compact("posts"));
This can be combined with the with() method if desired:
return view("blog", compact("posts"))->with("message", "Comment posted");
Documentation is available here.

If you want to pass just one variable to view, you may use
In Controller
return view('blog')->withTitle('Laravel Magic method.');
In view
<div>
Post title is {{$title}}.
</div>
If you want to pass multiple variables to view, you may use
In Controller
return view('blog')->withTitle('Laravel magic method')->withAuthor('Mister Tandon');
In view
<div>
Post title is {{$title}}.Author Name is {{$author}}
</div>

You can also pass an array as the second argument after the view template name, instead of stringing together a bunch of ->with() methods.
return View::make('blog', array('posts' => $posts));
Or, if you're using PHP 5.4 or better you can use the much nicer "short" array syntax:
return View::make('blog', ['posts' => $posts]);
This is useful if you want to compute the array elsewhere. For instance if you have a bunch of variables that every controller needs to pass to the view, and you want to combine this with an array of variables that is unique to each particular controller (using array_merge, for instance), you might compute $variables (which contains an array!):
return View::make('blog', $variables);
(I did this off the top of my head: let me know if a syntax error slipped in...)

Tips1:
Using With(), This is a best practice
return view('about')->withName('Author Willson')->withJob('Writer');
return View::make('home')->with(compact('about'))
return View::make('home')->with('comments', $comments);
Tips2:
Using compact()
return view(about, compact('post1','post2'));
Tips3:
Using Second Parameters:
return view("about", ["comments"=>$posts]);

controller:
use App\your_model_name;
funtion index()
{
$post = your_model_name::all();
return view('index')->with('this_will_be_used_as_variable_in_views',$post);
}
index:
<h1> posts</h1>
#if(count($this_will_be_used_as_variable_in_views)>0)
#foreach($this_will_be_used_as_variable_in_views as $any_variable)
<ul>
<p> {{$any_variable->enter_table_field}} </p>
<p> {{$any_variable->created_at}} </p>
</ul>
#endforeach
#else
<p> empty </p>
#endif
Hope this helps! :)

use TCG\Voyager\Models\Jobtype;
class FormController extends Controller
{
public function index()
{
$category = Jobtype::all();
return view('contact', compact('category'));
}
}
use your model
assign it to a variabel
pass the object to the view
Here is an example:

You can also do the same thing in another way,
If you are using PHP 5.5 or latest one then you can do it as follow,
Controller:
return view(index, compact('data1','data2')); //as many as you want to pass
View:
<div>
You can access {{$data1}}. [if it is variable]
</div>
#foreach($data1 as $d1)
<div>
You can access {{$d1}}. [if it is array]
</div>
#endforeach
Same way you can access all variable that you have passed in compact function.
Hope it helps :)

You can also do like this
$arr_view_data['var1'] = $value1;
$arr_view_data['var2'] = $value2;
$arr_view_data['var3'] = $value3;
return view('your_viewname_here',$arr_view_data);
And you access this variable to view as $var1,$var2,$var3

You can pass data to the view using the with method.
return view('greeting', ['name' => 'James']);

You can pass your table data to view using compact.
$users = RoleModel::get();
return view('super-admin',compact('users'));

You can also write for passing multiple data from your controller to a view
return \View::make('myHome')
->with(compact('project'))
->with(['hello'=>$hello])
->with(['hello2'=>$hello2])
->with(['hello3'=>$hello3]);

OK all the answers tell you how to pass data to the view but no one explains how to read it in the view .
if you use :
//Routes/web.php
...
Route::get('/user', function () {
return view('profile', [
'variable1' => 'value1' ,
'variable2'=> 'value2' , // add as much as you want
]);
});
To read these variables use in your views (in this example it's profile.blade.php file):
#if($variable1)
<p> variable1 = {{ $variable1 }}</p>
#endif
Laravel does all the necessary work and creates $variable1 for you .

For example, you have an array with your data.
$array1 = $data;
$array2 = $data;
From your controller you can pass this variable using compact. You can pass as many array as you want.
return view('data.index',compact('array1','array2'));
Here data is a folder in view and index is the file with extension index.blade.php
In view you can call the arrays like this
#foreach ($array1 as $something)
// some operation
#endforeach

For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way
In the controller, you define the variables you want to pass as global and you attribute the values to these variables.
Example global $variable; $variable = 1;
And now in the view, at the top, simply do
<?php global $variable;?>
Then you can now call your variable from any where in the view for example
{{$variable}}
hope this helps someone.

Related

Undefined foreach variable laravel

hello guys im having a problem with passing variable from my controller to views, as it does not identify its variable, here is my code:
RegisterController.php
use App\angkatan;
public function index()
{
$select = Angkatan::all();
return view('/auth/register')->with('name', $select);
}
My Route
web.php
Route::get('register', 'RegisterController#index');
and my view
register
#foreach($name as $ps)
#endforeach
the error say
Undefined variable: name (0)
im very thankful if anyone can help
You are just passing the wrong way $select variable to your view.
when you use Illuminate\View\View::with method you should pass an associative array which as key => value pairs
return view('/auth/register')->with(['name' => $select]);
You can also use compact which allows to pass variable which are accessible inside of the scope of your controller to the view and the string passed as argument to that function will be the name of variable accessible inside of the view file
$select = Angkatan::all();
return view('/auth/register', compact('select'));
You can not pass the variable in this way to the view. You have to pass an array in the second parameter of the with() method - it should be something like this:
return view('greeting', ['name' => 'James']);
return view('/auth/register', ['name' => $select]);
you can pass a second massive parameter to the view,
and also in with method, you need to pass massive as I remember.

How to send data to the view using redirect with Laravel without using Session?

I want to send data from the controller to my view without using session to get the data in the view.
In this question, they suggested to use return redirect('home')->with(['data' => $value]); but I have to use Session::get('data') in my view.
I know that it can be solved by using return view('myView')->with('data', 'value') but I want the URL to be changed to www.myurl.com/home when navigating to the home page and I cannot perform this with view('myView')->with('data', 'value').
Thank you !
There's no other way, you really need to use Session::get. However, we can do a workaround it, but it's messy.
// some controller function
return redirect('home')->with(['data' => $value]);
Now in your home controller function, do this:
SomeController#home
...
$data = [];
// if you need to pass other data to view, put it in data[]
// e.g., $data['username'] = Auth::user()->username;
if (Session::has('data')) {
$data['data'] = Session::get('data');
}
return view('myView', compact($data));
There, in your view you can just check if data is set.
<!-- myView.blade.php -->
<span>{{ isset($data) ? $data : '' }}</span>
For me, it's merely the same as accessing the Session from the view, because if you did, this is what your view will look like.
<!-- myView.blade.php -->
<span>{{ Session::has('data') ? Session::get('data') : '' }}</span>
You can also use session() global helper instead of the Session facade.

very confused with passing data array from controller to view in laravel or calling it from the view

ok I have my route to my controller (for future crud maybe angular use)
public function Dashboard_Clicks()
{
$DBClicks = DB::table('TotalClicks')->select('Total_Clicks')->get();
return view::('dashboard.pages')->with('$DBClicks', Total_Clicks);
do I use view composer? or another clean simple way to call this in?
}
this has one result a number 45454
I want to be able to get this result in my view like so.
<h1 class="clicks"><strong>{{ $DBClicks->Total_Clicks }} </strong> </h1>
You can try this: (Laravel 5)
return view('dashboard.pages', ['Total_Clicks' => $DBClicks]);
As far as I can recall there are two ways of passing data from controller to views first is compacting the variable in your controller and it will available as it is in your view. An example for the same is following:
$variable = 'somedata';
$array = ['some' => 'data'];
return view('viewName', compact('variable', 'array'));
//now in your view you can access {{$variable}} and #foreach($array as $something)
Second is with :
return view('viewName')->with(['first_var' => $variable, 'first_array' => $array])
//now in your view you can access {{$first_var}} and #foreach($first_array as $array)

How to pass data to view in Laravel?

Im passing data to my blade view with return View::make('blog', $posts); and in my blade view I'm trying to run an #foreach ($posts as $post) I end up with an error saying that $posts isn't defined.
My question is how would the $posts array be called?
You can pass data to the view using the with method.
return View::make('blog')->with('posts', $posts);
As of Laravel 5, the View::make() facade method from the 2013 accepted answer has been deprecated. Passing data to the view is now done using the view() helper function like this:
return view("blog", ["posts"=>$posts]);
Or, the same thing:
return view("blog", compact("posts"));
This can be combined with the with() method if desired:
return view("blog", compact("posts"))->with("message", "Comment posted");
Documentation is available here.
If you want to pass just one variable to view, you may use
In Controller
return view('blog')->withTitle('Laravel Magic method.');
In view
<div>
Post title is {{$title}}.
</div>
If you want to pass multiple variables to view, you may use
In Controller
return view('blog')->withTitle('Laravel magic method')->withAuthor('Mister Tandon');
In view
<div>
Post title is {{$title}}.Author Name is {{$author}}
</div>
You can also pass an array as the second argument after the view template name, instead of stringing together a bunch of ->with() methods.
return View::make('blog', array('posts' => $posts));
Or, if you're using PHP 5.4 or better you can use the much nicer "short" array syntax:
return View::make('blog', ['posts' => $posts]);
This is useful if you want to compute the array elsewhere. For instance if you have a bunch of variables that every controller needs to pass to the view, and you want to combine this with an array of variables that is unique to each particular controller (using array_merge, for instance), you might compute $variables (which contains an array!):
return View::make('blog', $variables);
(I did this off the top of my head: let me know if a syntax error slipped in...)
Tips1:
Using With(), This is a best practice
return view('about')->withName('Author Willson')->withJob('Writer');
return View::make('home')->with(compact('about'))
return View::make('home')->with('comments', $comments);
Tips2:
Using compact()
return view(about, compact('post1','post2'));
Tips3:
Using Second Parameters:
return view("about", ["comments"=>$posts]);
controller:
use App\your_model_name;
funtion index()
{
$post = your_model_name::all();
return view('index')->with('this_will_be_used_as_variable_in_views',$post);
}
index:
<h1> posts</h1>
#if(count($this_will_be_used_as_variable_in_views)>0)
#foreach($this_will_be_used_as_variable_in_views as $any_variable)
<ul>
<p> {{$any_variable->enter_table_field}} </p>
<p> {{$any_variable->created_at}} </p>
</ul>
#endforeach
#else
<p> empty </p>
#endif
Hope this helps! :)
use TCG\Voyager\Models\Jobtype;
class FormController extends Controller
{
public function index()
{
$category = Jobtype::all();
return view('contact', compact('category'));
}
}
use your model
assign it to a variabel
pass the object to the view
Here is an example:
You can also do the same thing in another way,
If you are using PHP 5.5 or latest one then you can do it as follow,
Controller:
return view(index, compact('data1','data2')); //as many as you want to pass
View:
<div>
You can access {{$data1}}. [if it is variable]
</div>
#foreach($data1 as $d1)
<div>
You can access {{$d1}}. [if it is array]
</div>
#endforeach
Same way you can access all variable that you have passed in compact function.
Hope it helps :)
You can also do like this
$arr_view_data['var1'] = $value1;
$arr_view_data['var2'] = $value2;
$arr_view_data['var3'] = $value3;
return view('your_viewname_here',$arr_view_data);
And you access this variable to view as $var1,$var2,$var3
You can pass data to the view using the with method.
return view('greeting', ['name' => 'James']);
You can pass your table data to view using compact.
$users = RoleModel::get();
return view('super-admin',compact('users'));
You can also write for passing multiple data from your controller to a view
return \View::make('myHome')
->with(compact('project'))
->with(['hello'=>$hello])
->with(['hello2'=>$hello2])
->with(['hello3'=>$hello3]);
OK all the answers tell you how to pass data to the view but no one explains how to read it in the view .
if you use :
//Routes/web.php
...
Route::get('/user', function () {
return view('profile', [
'variable1' => 'value1' ,
'variable2'=> 'value2' , // add as much as you want
]);
});
To read these variables use in your views (in this example it's profile.blade.php file):
#if($variable1)
<p> variable1 = {{ $variable1 }}</p>
#endif
Laravel does all the necessary work and creates $variable1 for you .
For example, you have an array with your data.
$array1 = $data;
$array2 = $data;
From your controller you can pass this variable using compact. You can pass as many array as you want.
return view('data.index',compact('array1','array2'));
Here data is a folder in view and index is the file with extension index.blade.php
In view you can call the arrays like this
#foreach ($array1 as $something)
// some operation
#endforeach
For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way
In the controller, you define the variables you want to pass as global and you attribute the values to these variables.
Example global $variable; $variable = 1;
And now in the view, at the top, simply do
<?php global $variable;?>
Then you can now call your variable from any where in the view for example
{{$variable}}
hope this helps someone.

CodeIgniter get_where

I’m attempting to use get_where to grab a list of all database records where the owner is equal to the logged in user.
This is my function in my controller;
function files()
{
$owner = $this->auth->get_user();
$this->db->get_where('files', array('owner =' => '$owner'))->result();
}
And in my view I have the following;
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
When I try accessing the view, I get the error :
Fatal error: Call to a member function result() on a non-object in /views/account/files.php on line 1.
Wondered if anyone had any ideas of what might be up with this?
Thanks
CodeIgniter is a framework based on MVC principles. As a result, you would usually separate application logic, data abstraction and "output" into their respective areas for CodeIgniter use. In this case: controllers, models and views.
Just for reference, you should usually have you "data" code as a model function, in this case the get_where functionality. I highly suggest you read through the provided User Guide to get to grips with CodeIgniter, it should hold your hand through most steps. See: Table of Contents (top right).
TL;DR
To solve your problem you need to make sure that you pass controller variables through to your view:
function files()
{
$owner = $this->auth->get_user();
$data['files'] = $this->db->get_where('files', array('owner =' => '$owner'))->result();
$this->load->view('name_of_my_view', $data);
}
And then make sure to use the correct variable in your view:
<?php foreach($files as $row): ?>
<span><?=$row['name']; ?></span>
<?php endforeach; ?>
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Remove the result function like so.
<?php foreach($query as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Btw. It's a much better idea to test the query for a result before you return it.
function files()
{
$owner = $this->auth->get_user();
$query = $this->db->get_where('files', array('owner =' => $owner))->result();
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;
}
public function get_records(){
return $this->db->get_where('table_name', array('column_name' => value))->result();
}
This is how you can return data from database using get_where() method.
All querying should be performed in the Model.
Processing logic in the View should be kept to an absolute minimum. If you need to use some basic looping or conditionals, okay, but nearly all data preparation should be done before the View.
By single quoting your $owner variable, you convert it to a literal string -- in other words, it is rendered as a dollar sign followed by five letters which is certainly not what you want.
The default comparison of codeigniter's where methods is =, so you don't need to declare the equals sign.
I don't know which Auth library you are using, so I'll go out on a limb and assume that get_user() returns an object -- of which you wish to access the id of the current user. This will require ->id chained to the end of the method call to access the id property.
Now, let's re-script your MVC architecture.
The story starts in the controller. You aren't passing any data in, so its duties are:
Load the model (if it isn't already loaded)
Call the model method and pass the owner id as a parameter.
Load the view and pass the model's returned result set as a parameter.
*Notice that there is no querying and no displaying of content.
Controller: (no single-use variables)
public function files() {
$this->load->model('Files_model');
$this->load->view(
'user_files',
['files' => $this->Files_model->Files($this->auth->get_user()->id)]
);
}
Alternatively, you can write your controller with single-use variables if you prefer the declarative benefits / readability.
public function files() {
$this->load->model('Files_model');
$userId = $this->auth->get_user()->id;
$data['files'] = $this->Files_model->Files($userId);
$this->load->view('user_files', $data);
}
Model: (parameters are passed-in, result sets are returned)
public function Files($userId) {
return $this->db->get_where('files', ['owner' => $userId])->result();
}
In the above snippet, the generated query will be:
SELECT * FROM files WHERE owner = $userId
The result set (assuming the query suits the db table schema) will be an empty array if no qualifying results or an indexed array of objects. Either way, the return value will be an array.
In the final step, the view will receive the populated result set as $files (the variable is named by the associative first-level key that was declared in the view loading method).
View:
<?php
foreach ($files as $file) {
echo "<span>{$file->name}</span>";
}
The { and } are not essential, I just prefer it for readability in my IDE.
To sum it all up, the data flows like this:
Controller -> Model -> Controller -> View
Only the model does database interactions.
Only the view prints to screen.

Categories