Laravel return Response::view - php

Simple question, I think.
I have a route that calls a function in a controller. In that controller, I have a call to another controller function.
For example:
$_testing = with(new TestingController)->prepwork($variable1,$variable2);
Inside of TestingController prepwork(), if a condition matches, I
return Response::view(...);
Question - how come that isn't enough? the return just returns control back to the calling function (which makes sense), but how do I tell Laravel - stop what you are doing and output that view.
To make it work, I have to:
$_testing = with(new TestingController)->prepwork($variable1,$variable2);
return $_testing;
That doesn't really work as the prepwork is designed to do some heavy lifting and then output a result model. The view is only kicked off when there is an error.
And YES - I know I can do something like this:
if ($_testing->whatImCheckingForErrors) { return Response::view(...); }
I'm just trying to understand why the return Response::view doesn't end the processing... If that makes sense.

Only the very last return will end processing, because the application will receive this last return and render whatever you send in it.
If you call a method (1), that calls another method (2), that calls a third one (3), Laravel app will receive the View only when your return back from (1).
That's why when you added that last return it worked.
There are things you can do, like:
echo Response::view(...);
die;
It may work sometimes, but
BUT THIS IS REALLY BAD, DO NOT DO THIS UNLESS YOU'RE JUST TESTING THINGS!
Because Laravel won't be able to close everything and flush whatever it needs to and you can compromise your application and even server.

Related

how to use DD() method in Laravel projects?

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) }}

How do I check functions that should never return false?

Background:
Inside large controllers I will have a number of different functions being called, to create a user, to update their order, to schedule in an event. Each of these operations are handled by a function in the model layer... here is an example of one of those functions:
$user_id = 1;
$data = array('name' => 'Billy');
if (updateUser($user_id, $data) === false) {
// handle error?
}
// continue with rest of controller
Problem:
I finally took a reality check today and realised that I have no good reason for coding like this...
If updateUser() returns false then something has seriously gone wrong with my Database Abstraction Layer that has prevented me from updating data in my database. This should never happen and therefore there are no practical errors to show my users anyway (that would allow them to take appropriate actions).
Basically my app is fundamentally broken at that point.
Question:
Should I bother to check functions that should never return false? If so how? Or should I just call them like this without any checks?
updateUser($foo)
createBooking($bar)
scheduleEvent($qux)
When something happens inside a function that should never happen, throw an exception.
And then you can handle (catch) all exceptions where you want to do that. For example by showing a friendly message to the user and logging all details for yourself so that you know what went wrong and where.
Then you can get rid of the if statements and only use these when there are valid / normal options.

How to check the whole chain of relational chain without check each method separately?

I often get an FatalErrorException that says Call to a member function method() on null. This happens mostly when I use (in blade) long chained sentences where one among them (models) is null. For example:
$file->owners()->first()->categories()->first()->title
so when for example here categories returns null I get this exception. I have to check each method one by one. I can't check them at a time like:
!empty($file->owners()->first()->categories()->first()->title)
!is_null($file->owners()->first()->categories()->first()->title)
isset($file->owners()->first()->categories()->first()->title)
count($file->owners()->first()->categories()->first()->title)
I still get the exception by using these, because (I guess) before getting the final parameter (here 'title') the process goes trough all methods and before it can't get to the final one the exception comes. Actually in controllers this could be guidable to make all these checks but in blade this does not come so relevant to me. Besides, this is a loop. So I am looking how I could do this check at once.
Well if you get null from the first first() call you cannot continue the method chaining. You can always use try ... catch:
try {
$file->owners()->first()->categories()->first()->title
} catch (\Exception $e) {
// do on fail
}
I'd recommend using View Presenter in your project. It really helps you to keep your code clean by moving all extra logic from your views and put it in a dedicated presenter class.
Watch this laracasts video to learn more.

Laravel 5 get command response

I think I understand the concept of command in Laravel, in that it's a good place to put reuseable code, that can be called from controllers and the like, but I have a query:
Can I return a value back to the calling method from a command? For example, I have a controller method which creates a user in Active Directory, for which there is a command to do this. If the AD server is unreachable, I want to return a response back to the calling controller method. Is this possible?
It only shows in the documentation how to call a command using dispatch(), but nothing as to whether it can return anything.
And if you cannot return a value, can someone explain the reasoning behind why you wouldn't want to return a value? I know that queued commands may take a while and wouldn't be appropriate to wait for a response, but for commands that should be executed immediately I don't see why you wouldn't want to return a value.
Any help or advice is appreciated.
In the context of the command bus, yes you can return values on non-queued commands. In your command handler method, simply return what you want:
public function handle(){
return 'foobar';
}
And save the result of your dispatch command to a variable:
$my_command_result = $this->dispatch(
new MyCommand();
);
Commands are not for storing reusable code in controllers. Theyre getting renamed to jobs in 5.1 and their main purpose it to work as Cron Jobs. If you have a method to create a user and want to use it in many places, you could store it in the User model.

Is it considered a good practice to put a redirection method into another one?

For example, if you have to redirect in almost every controller, is it a good practice to put that into another method and use it from there?
E.g. There's always this line of code:
return Redirect::route($route)->with('err_msg', 'Some error');
Is it better to put that into, let's say, and AdminController and call it from there passing only the error message and the route you want it to be redirected to?
Doesn't really make a difference since you will just be calling a "helper" function and then in that function you will still be calling the Redirect each time.
Let's say you create:
function redirect_user($route,$error_msg)
{
return Redirect::route($route)->with('err_msg', $error_msg);
}
Unless you want the helper to do something else (like validate the $route, format/log the error) in a generic way particular to your application's needs, there is no real need to complicate things by introducing an extra function() call doing practically nothing more than wrapping the redirect

Categories