Laravel pass data between views - laravel

I have a view with a few variables that I want to pass to a new page and prepopulate a form with them.
$data->title
$data->catid
$data->category
$data->groupName
The "vanila way I could make a url like something.com?var1=something&var2=something etc.
But how can I do this in laravel?

Considering you can redirect to a page with GET parameter. For example, "something.com?var1=something&var2=something", You can actually pass this data to another view in Laravel. Let's assume you want to pass var1 and var2 variables to another view.
You will redirect user to the URL containing two variables as GET parameters, You will also execute Controller function that will handle that route. Let's assume that following is your web.php or routes.php file.
Route::get('firstpage","SomeController#view1");
Route::get("secondpage","SomeController#view2");
Now, in view2 method of the SomeController, You can check if those variables exist or not. Here is an example of var1 and var2.
public function view2()
{
if(isset($_GET['var1'])){
$var1 = $_GET['var1'];
}
// Similar for var2
}
This is how you can pass variables between views.

The best way IMHO is using sessions.
session()->put('data', $data);
And to retrieve it and to check if the key exists:
if (session()->has('data')) {
$data = session('data'); //array
}
If you use the $data in session() only once you can pull it session()->pull('data'); //array
A word of caution if you use database sessions. You may have to change the field 'payload' from TEXT to MEDIUMTEXT if $data holds larger amounts of data.
The use of sessions is not search engine (SEO) friendly. If that matters, the easiest way to make the url is $str = http_build_query($data); and to build the url \URL()->route('your.route').'?'.$str;
To access the data from the URL: $title = \Request::query('title');

Related

Passing variables to views in Laravel

In CodeIgniter you can pass a data array to views as in:
$this->load->view("view_name", array("key" => "value"));
and then access the variable in the view simply as $variable_name.
I'm trying to achieve the same thing in Laravel without necessarily storing the data in the session. The answers that I've seen suggest doing something like:
return view("view_name")->with("variable_name", $variable_value);
But doesn't that store it in the session? I'm looking to simply pass the variables directly to the view so as to avoid cluttering up the session with things that I'm passing to various views from controller methods.
Any help is much appreciated! Thanks.
You can use compact() to pass an array of the variables in your controller to your view. The compact() function will create an array from the variable names passed into it.
Controller class
public function showDashboard()
{
$total_sales = Sale::sum('price');
$average_sales = Sale::avg('price');
return view('dashboard.show',compact('total_sales','average_sales'));
}
blade file
<p>
Total sales made is {{$total_sales}} at average of {{$average_sales}}
</p>

How to access table data without model in view

I want to know is there any way to access table data without passing it from controller to view in laravel 5 ?
I have an Options table in my database that stores all my project options. it has three column:
id
name
value
Now I want to access each option value in my master.blade.php file.
what is the best way to do it.
If you understand what MVC is all about then you should know that passing a variable from controller to your view is the best practice. View is simply used for presentation and should only be used for presentation purpose for the sake of separation of concern.
With that been said the best approach is:
Create a model for options then pass it through your controller to the view.
For example:
use App\Option;
PageController extends Controller{
public function __construct(Option $option){
$this->option = $option;
}
public function about(){
$options = $this->option->list('id','value');
return view('about', $options);
}
}
To make variable global in all view see my answer here:
Laravel 5 - global Blade view variable available in all templates
Well there can be multiple ways available, but passing your Table data directly into views is not a recommended way, It would be much better if you follow the proper way, means from Controller to Model. Well its upto you. here is my suggested possible ways.
Method 1 (about which you are asking)
in your master.blade.php file, you can also do this,
<?php
$v = new \App\Message(); // your model object
echo $v ->testmeee(); // its method
?>
Method 2
If you are trying to use your Table data globally(means you want options data should be available on all pages/views), then this one is highly suggested way.
Goto your App/Http/Providers/AppServiceProvider.php file
view()->composer('*', function ($view)
{
$user = new \App\User();
$view->with('friend_new_req_count', count($user->getLoggedinUserNewFriends()));
});
now this variablefriend_new_req_count with data would be available in all views (only in views) means you can access in view {{$friend_new_req_count}}

Is good practice for view sending param by assign to controller property?

For sending param to view, document in CodeIgniter use as following:
$data['name'] = $this->name;
$data['color'] = $this->color;
$this->load->view('you_view',$data);//Load view with $data param
But currently i use like this:
//Controller file
$this->params = [Big Object or Array ];//Here I assigned my OJBECT or Array to controller property PARAMS
$this->load->view('you_view');//***** Wthout send with load view*******
//View file
$var_dump($this->params);//Notice after I print_r( $this) i found that it is current controller, that why i use without sending params during load view, but i afraid any problem or make my system slow.
In many different ways you can pass variables to the view, for example through controller as you did, then through config file, model, language file, or defining a variables with define(), but then the point of MVC model was to separate data, logic and design, so i don't thing your way is a bad way, just not in the spirit of idea of MVC. Do you get any better performance?

How to build an anchor in CodeIgniter where you want to change a variable that is already present in the URI?

Normally I would just use URL GET parameters but CodeIgniter doesn't seem to like them and none of the URL helper functions are designed for them, so I'm trying to do this the 'CodeIgniter way'.
I would like to build a page where the model can accept a number of different URI paramters, none necessarily present, and none having to be in any particular order, much like a regular URL query string with get parameters.
Let's say I have the following url:
http://example.com/site/data/name/joe/
Here not including the controller or the method there would be one parameter:
$params = $this->uri->uri_to_assoc(1);
print_r($params);
// output
array( [name] => [joe] )
If I wanted 'joe' to change to 'ray' I could do this:
echo anchor('name/ray');
Simple enough but what if there are more parameters and the position of the parameters are changing? Like:
http://example.com/site/data/town/losangeles/name/joe/
http://example.com/site/data/age/21/name/joe/town/seattle
Is there a way to just grab the URL and output it with just the 'name' parameter changed?
Edit: As per landons advice I took his script and set it up as a url helper function by creating the file:
application/helpers/MY_url_helper.php
Basically I rewrote the function current_url() to optionally accept an array of parameters that will be substituted into the current URI. If you don't pass the array the function acts as originally designed:
function current_url($vars = NULL)
{
$CI =& get_instance();
if ( ! is_array($vars))
{
return $CI->config->site_url($CI->uri->uri_string());
}
else
{
$start_index = 1;
$params = $CI->uri->uri_to_assoc($start_index);
foreach ($vars as $key => $value)
{
$params[$key] = $value;
}
$new_uri = $CI->uri->assoc_to_uri($params);
return $CI->config->site_url($new_uri);
}
}
It works OK. I think the bottom line is I do not like the 'CodeIgniter Way' and I will be looking at mixing segment based URL's with querystrings or another framework altogether.
You can use the assoc_to_uri() method to get it back to URI format:
<?php
// The segment offset to use for associative data (change me!)
$start_index = 1;
// Parse URI path into associative array
$params = $this->uri->uri_to_assoc($start_index);
// Change the value you want (change me!)
$params['name'] = 'ray';
// Convert back to path format
$new_uri = $this->uri->assoc_to_uri($params);
// Prepend the leading segments back to the URI
for ($i=1; $i<$start_index; $i++)
{
$new_uri = $this->uri->segment($i).'/'.$new_uri;
}
// Output anchor
echo anchor($new_uri);
I'd recommend wrapping this in a helper function of some sort. Happy coding!
Why not use CodeIgniter's built in URI Class? It allows you to select the relevant segments from the URL which you could use to create the anchor. However, unless you created custom routes, it would mean that your methods would need to accept more parameters.
To use the URI Class, you would have the following in your method:
echo anchor($this->uri->segment(3).'/ray');
Assuming /site/data/name are all CodeIgniter specific (/controller/method/parameter)
Now, I think this could be made a lot easier if you were using routes. Your route would look like this:
$route['site/data/name/(:any)'] = 'site/data/$1';
Effictively, your URL can be as detailed and specific as you want it to be, but in your code the function is a lot cleaner and the parameters are quite descriptive. You method would defined like this:
function data($name) { }
To extend your route to accept more parameters, your route for the the example URL "http://example.com/site/data/age/21/name/joe/town/seattle" you supplied would look like this:
$route['site/data/age/(:num)/name/(:any)/town/(:any)'] = 'controller/data/$1/$2/$3';
And your function would look like this:
function data($age, $name, $town) { }

filter a string to remove disallowed characters to compose an URL in CodeIgniter

I'm trying to make URL-friendly links for the blog on my portfolio.
So I would like to obtain links something like site/journal/post/{title}
Obviously Journal is my controller, but let's say my title would be 'mysite.com goes live!' I would like to have a valid url like site/journal/post/mysitecom-goes-live where all disallowed characters are removed.
How would I transform 'mysite.com goes live!' to 'site/journal/post/mysitecom-goes-live' in CodeIgniter based on the characters in $config['permitted_uri_chars']
use the url helper
$this->load->helper('url');
$blog_slug = url_title('Mysite.com Goes live!');
echo $blog_slug //mysitecom-site-goes-live
// might differ slightly, but it'll do what you want.
to generate url-friendly links.
Store this value in a field in your blog table (url_title/url_slug) whatever.
make a function:
class Journal extends controller
{
//make your index/constructor etc
function view($post)
{
$this->blog_model->get_post($post);
// etc - your model returns the correct post,
// then process that data and pass it to your view
}
}
your blog_model has a method get_post that uses CI's
$this->db->where('url_title', $post);
hope that makes sense.
then when you access the page:
site.com/journal/view/mysite-goes-live
the function will pick up "mysite-goes-live" and pass it to the view() function, which in turn looks up the appropriate blog entry in the database.

Resources