I know that for some it might be stupid or funny question (but I am newbie) but I need to find know how to properly use DD() method in laravel projects.
For example - I have got tasks to debug some code and functionality in my project (PHP laravel). And it always takes me for ever to find the exact file or folder or code where the problem is.
My mentor says to use DD() method to find things faster (but for learning purposes he didn't explain me a lot about how to actually use it and said to find out my self), but said that I should start with Route (we use backpack as well for our project). So after finding Route (custom.php file) which controller connects to my required route what should I do next? How do I implement dd() method (or as my mentor says dd('call here') method) to fast find what I should be looking for to solve my problem and complete my task? Where should I write this dd() and how should I write it?
Thank you for the answer in advance!
for example I have a:
public function create(): View
{
return view('xxxxxx. \[
//
//
\]);
}
and if I put dd() anywhere in the code, I get error message in my URL :(
first of all ,in Laravel we use dd() before return in order to read any variable.
in controller we often use two kinds of variables : collection(which we get its members via foreach) or singular variable (we get it via its name)for example:$var = 1; dd($var).
notice:
if you are using ajax response you will not be able to see dd() results in page ,you can see the result via network tab in your browser (if u inspect your page).
dd stands for "Dump and Die."
Laravel's dd() function can be defined as a helper function, which is used to dump a variable's contents to the browser and prevent the further script execution.
Example:
dd($users,$variable1,$var2);
You can use dd() in blade
#foreach($users as $user)
#dd($user)
OR
{{dd($user)}}
#endforeach
#dd($var1)
You can read this article, the have more example and comparison
https://shouts.dev/articles/laravel-dd-vs-dump-vs-vardump-vs-printr-with-example
As Laravel is following model-view-controller or MVC design pattern. First go to the route and check which controller is called in the URL with the related URL.
Then go to the controller. **dd**() function is basically a dump and die. you also can do this by **print** or **echo** function too.
Lets assume that I have a controller name ProductController where I have method name index.From where I need to show a list of products in a table.
// in controller
public function index()
{
$products = Products::all();
// here you think ,I need to check whether I am getting the output or
not.
dd( $products );
//Or echo $products;
return view ('product.list',compact('products'));
}
let's suppose you are getting everything but in view when you loop through the products you declare the wrong variable name or mistakenly do some spelling mistakes. and want to see the result.
In view just do the dd() method by the following way:
{{ dd($products) }}
I have the below content in my DB-
<p>This is dummy content for testing</p>
{{LandingPageController::getTest()}}
I want to render that into my view. But when I'm rendering this in Laravel view, this {{LandingPageController::getTest()}} is getting displayed as it is stored in DB.
I want to call the LandingPageController getTest method in my view.
Please suggest me a quick fix for this.
Landing Page Controller
public function getTest(){
return "Hello World!!!";
}
just make the function static
public static function getTest(){
return "Hello World!!!";
}
that's the only way you can call it like this {{LandingPageController::getTest()}} but I do advice not to do that in your blade file this not a good code design. you should do $test = LandingPageController::getTest() in the controller that you return the blade view and pass it like this return view('blade_file_name',compact('test')) and in your blade file just do {{$test}}
PS - if you doing it your controller use the class like this use Path\To\Controller\LandingPageController
Use namespace for that controller in your blade file. example
namespace App\Http\Controllers\LandingPageController;
You can evaluate a string as a php code using the eval() function
eval — Evaluate a string as PHP code
But it is highly discouraged.
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
You can use a generic string, {test} for example, when saving the content in the storage.
<p>This is dummy content for testing</p>
{test}
Then whenever you need to display the actual content, you can simply replace the generic string with the real value. You'll have this line in your blade file:
{{ str_replace('{str}', "Hello World", $content) }}
Take a look at Helper. You can call helper function in view to render your text or html
Got the solution, achieve the functionality with "laravel-shortcodes".
Found a very good tutorial on laravel-shortcodes like wordpress
I am trying to figure out how to do the equivalent of the following in Laravel that I would do in CodeIgniter all the time to build views:
$section = $this->load->view('pages/about', $data, TRUE);
This would allow me to echo $section in another view file and then when that view was called the normal way, it would render it. I am not sure how to do something like this in Laravel.
UPDATE
I figured it out. What I was needing was Laravel's HtmlString class to take a string and convert it to html markup to the view file.
You would need to use the View Facade, so make sure to include it with an "Use" statement in your Controller, but basically is this:
$html = View::make('pages/about', $data)->render();
The render() method will just render the view in HTML, instead of returning it as a Response object like the view() helper function does.
There are several ways to do so, try this:
return view('admin.profile', $data);
Read through this doc:
https://laravel.com/docs/5.5/views
I am trying to make a counter in my laravel site. This counter takes all the comments from model Comments which were created from Carbon::now() until startofMonth(). So I have my controller and function counter as so:
class CommentsController extends Controller
{
public function counter()
{
$new_comments=Comments::where('created_at', Carbon::now()->startofMonth())->get();
$counted->count($new_comments['created_at']);
return View::make('pages.dashboard')->with('new_comments', $counted);
}
}
My blade template:
<div class="row">
<div class="col-xs-3">
<i class="fa fa-comments fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">{{!!$new_comments!!}}</div>
<div>New Comments!</div>
</div>
I keep getting a variable undefined error message even though the variable is called in the controller! The dashboard page works fine when the variable is not called in the blade template.
EDIT:
I have managed to get this working if ignore the controller and add the following into my view:
{{App\Comments::count()}}
This only shows the total amount of rows in the table Comments, but I will try and add the mySQL query in to it.
I still don't know why it can't be called as a variable from the controller.
In your blade template, you are calling it correctly but ! brings such issues {{!!$new_comments!!}} it will say variable undefined.
Try it without !!, It worked for me.
First: you want to take all comments are created from begin of month to now, you need a whereBetween query, not equal.
Second: You call a undefined variable $counted. I think you need remove
$counted->count($new_comments['created_at']);
and pass $new_comments to view instead of $counted
return View::make('pages.dashboard')->with('new_comments', $new_comments);
and display comments count in view
{{ $new_comments->count() }}
Hope this help you
This is a bit of a late answer, but I believe you're passing your variables incorrectly with the ->with() function. From my experience with Laravel, ->with() uses an array syntax for passing multiple variables to a view. For example:
return View::make('pages.dashboard')
->with(["new_comments" => $new_comments, "counted" => $counted]);
// Note the array usage, works with [] or array()
Then, in your dashboard.blade.php you can call either {{ $new_comments }} or {!! $new_comments !!} to echo out that value (one ignores HTML markup, one includes it.)
On a side note, trying to echo out the contents of an Eloquent collection (i.e. Comment::get() as opposed to something like Comment::first()) may not work. You should loop over the results and echo accordingly:
#foreach($new_comments AS $new_comment)
{!! $new_comment->created_at !!}
...
#endforeach
This was solved. I was calling the return view::make(dashboard) in another (page)controller. This controller took precedent therefore this view did not occur. Therefore in my pagecontroller I applied the following:
public function dashboard()
{
$count = Comments::where('created_at', '>', Carbon::today())->count();
return View::make('pages.dashboard')->with('new_comments_count', $count);
}
I can then call new_comments_count in my view.
Many thanks for the help.
I'm reading the Laravel Blade documentation and I can't figure out how to assign variables inside a template for use later. I can't do {{ $old_section = "whatever" }} because that will echo "whatever" and I don't want that.
I understand that I can do <?php $old_section = "whatever"; ?>, but that's not elegant.
Is there a better, elegant way to do that in a Blade template?
EASY WAY
If you want to define multiple variables, use the full form of the blade directive:
#php
$i = 1;
$j = 2;
#endphp
If you only want to define one variable, you can also use a single PHP statement:
#php($i = 1)
MORE ADVANCED: ADD A 'DEFINE' TAG
If you want to use custom tags and use a #define instead of #php, extend Blade like this:
/*
|--------------------------------------------------------------------------
| Extend blade so we can define a variable
| <code>
| #define $variable = "whatever"
| </code>
|--------------------------------------------------------------------------
*/
\Blade::extend(function($value) {
return preg_replace('/\#define(.+)/', '<?php ${1}; ?>', $value);
});
Then do one of the following:
Quick solution: If you are lazy, just put the code in the boot() function of the AppServiceProvider.php.
Nicer solution:
Create an own service provider. See https://stackoverflow.com/a/28641054/2169147 on how to extend blade in Laravel 5. It's a bit more work this way, but a good exercise on how to use Providers :)
After the above changes, you can use:
#define $i = 1
to define a variable.
It is discouraged to do in a view so there is no blade tag for it.
If you do want to do this in your blade view, you can either just open a php tag as you wrote it or register a new blade tag. Just an example:
<?php
/**
* <code>
* {? $old_section = "whatever" ?}
* </code>
*/
Blade::extend(function($value) {
return preg_replace('/\{\?(.+)\?\}/', '<?php ${1} ?>', $value);
});
In laravel-4, you can use the template comment syntax to define/set variables.
Comment syntax is {{-- anything here is comment --}} and it is rendered by blade engine as
<?php /* anything here is comment */ ?>
so with little trick we can use it to define variables, for example
{{-- */$i=0;/* --}}
will be rendered by bladeas
<?php /* */$i=0;/* */ ?> which sets the variable for us.
Without changing any line of code.
There is a simple workaround that doesn't require you to change any code, and it works in Laravel 4 just as well.
You just use an assignment operator (=) in the expression passed to an #if statement, instead of (for instance) an operator such as ==.
#if ($variable = 'any data, be it string, variable or OOP') #endif
Then you can use it anywhere you can use any other variable
{{ $variable }}
The only downside is your assignment will look like a mistake to someone not aware that you're doing this as a workaround.
Ya'll are making it too complicated.
Just use plain php
<?php $i = 1; ?>
{{$i}}
donesies.
(or https://github.com/alexdover/blade-set looks pretty straighforward too)
We're all kinda "hacking" the system by setting variables in views, so why make the "hack" more complicated then it needs to be?
Tested in Laravel 4.
Another benefit is that syntax highlighting works properly (I was using comment hack before and it was awful to read)
Since Laravel 5.2.23, you have the #php Blade directive, which you can use inline or as block statement:
#php($old_section = "whatever")
or
#php
$old_section = "whatever"
#endphp
You Can Set Variables In The Blade Templating Engine The Following Ways:
1. General PHP Block
Setting Variable: <?php $hello = "Hello World!"; ?>
Output: {{$hello}}
2. Blade PHP Block
Setting Variable: #php $hello = "Hello World!"; #endphp
Output: {{$hello}}
You can set a variable in the view file, but it will be printed just as you set it. Anyway, there is a workaround. You can set the variable inside an unused section. Example:
#section('someSection')
{{ $yourVar = 'Your value' }}
#endsection
Then {{ $yourVar }} will print Your value anywhere you want it to, but you don't get the output when you save the variable.
EDIT: naming the section is required otherwise an exception will be thrown.
In laravel document https://laravel.com/docs/5.8/blade#php
You can do this way:
#php
$my_variable = 123;
#endphp
In Laravel 4:
If you wanted the variable accessible in all your views, not just your template, View::share is a great method (more info on this blog).
Just add the following in app/controllers/BaseController.php
class BaseController extends Controller
{
public function __construct()
{
// Share a var with all views
View::share('myvar', 'some value');
}
}
and now $myvar will be available to all your views -- including your template.
I used this to set environment specific asset URLs for my images.
Laravel 7 :
{{ $solution = "Laravel 7 is awesome and easy to use !!" }}
And suddenly nothing will appear.
From my experience, if you have to do something like this prepare the html in a model's method or do some reorganizing of your code in to arrays or something.
There is never just 1 way.
{{ $x = 1 ? '' : '' }}
In Laravel 5.1, 5.2:
https://laravel.com/docs/5.2/views#sharing-data-with-all-views
You may need to share a piece of data with all views that are rendered by your application. You may do so using the view factory's share method. Typically, you should place calls to share within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them.
Edit file: /app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
view()->share('key', 'value');
}
public function register()
{
// ...
}
}
I'm going to extend the answer given by #Pim.
Add this to the boot method of your AppServiceProvider
<?php
/*
|--------------------------------------------------------------------------
| Extend blade so we can define a variable
| <code>
| #set(name, value)
| </code>
|--------------------------------------------------------------------------
*/
Blade::directive('set', function($expression) {
list($name, $val) = explode(',', $expression);
return "<?php {$name} = {$val}; ?>";
});
This way you don't expose the ability to write any php expression.
You can use this directive like:
#set($var, 10)
#set($var2, 'some string')
You may use the package I have published: https://github.com/sineld/bladeset
Then you easily set your variable:
#set('myVariable', $existing_variable)
// or
#set("myVariable", "Hello, World!")
As for my elegant way is like the following
{{ ''; $old_section = "whatever"; }}
And just echo your $old_section variable.
{{ $old_section }}
If you have PHP 7.0:
The simple and most effective way is with assignment inside brackets.
The rule is simple: Do you use your variable more than once? Then declare it the first time it's used within brackets, keep calm and carry on.
#if(($users = User::all())->count())
#foreach($users as $user)
{{ $user->name }}
#endforeach
#else
There are no users.
#endif
And yes, I know about #forelse, this is just a demo.
Since your variables are now declared as and when they are used, there is no need for any blade workarounds.
Assign variable to the blade template, Here are the solutions
We can use <?php ?> tag in blade page
<?php $var = 'test'; ?>
{{ $var }
OR
We can use the blade comment with special syntax
{{--*/ $var = 'test' /*--}}
{{ $var }}
I also struggled with this same issue. But I was able to manage this problem by using following code segment. Use this in your blade template.
<input type="hidden" value="{{$old_section = "whatever" }}">
{{$old_section }}
I don't think that you can - but then again, this kind of logic should probably be handled in your controller and passed into the view already set.
I was looking for a way to assign a value to a key and use it many times in my view. For this case, you can use #section{"key", "value"} in the first place and then call #yield{"key"} to output the value in other places in your view or its child.
In laravel8
#php
$name="Abdul mateen";
{{ echo $name; }}
#endphp
Hacking comments is not a very readable way to do it. Also editors will color it as a comment and someone may miss it when looking through the code.
Try something like this:
{{ ''; $hello = 'world' }}
It will compile into:
<?php echo ''; $hello = 'world'; ?>
...and do the assignment and not echo anything.
It's better to practice to define variable in Controller and then pass to view using compact() or ->with() method.
Otherwise #TLGreg gave best answer.
There is a very good extention for Blade radic/blade-extensions. After you add it you can use #set(variable_name, variable_value)
#set(var, 33)
{{$var}}
In my opinion it would be better to keep the logic in the controller and pass it to the view to use. This can be done one of two ways using the 'View::make' method. I am currently using Laravel 3 but I am pretty sure that it is the same way in Laravel 4.
public function action_hello($userName)
{
return View::make('hello')->with('name', $userName);
}
or
public function action_hello($first, $last)
{
$data = array(
'forename' => $first,
'surname' => $last
);
return View::make('hello', $data);
}
The 'with' method is chainable. You would then use the above like so:
<p>Hello {{$name}}</p>
More information here:
http://three.laravel.com/docs/views
http://codehappy.daylerees.com/using-controllers
I had a similar question and found what I think to be the correct solution with View Composers
View Composers allow you to set variables every time a certain view is called, and they can be specific views, or entire view templates. Anyway, I know it's not a direct answer to the question (and 2 years too late) but it seems like a more graceful solution than setting variables within a view with blade.
View::composer(array('AdminViewPath', 'LoginView/subview'), function($view) {
$view->with(array('bodyClass' => 'admin'));
});
laravel 5 you can easily do this . see below
{{--*/ #$variable_name = 'value' /*--}}
You can extend blade by using the extend method as shown below..
Blade::extend(function($value) {
return preg_replace('/\#var(.+)/', '<?php ${1}; ?>', $value);
});
after that initialize variables as follows.
#var $var = "var"
inside the blade file, you can use this format
#php
$i++
#endphp