I have an $alerts variable array.
Look like this
array:3 [▼
0 => array:3 [▼
"status" => 200
"message" => "Success"
"data" => []
]
1 => array:3 [▼
"status" => 200
"message" => "Success"
"data" => []
]
2 => array:3 [▼
"status" => 404
"error_code" => 35
"message" => "invalid json - api not supported"
]
]
I want to send it from my controller to my view.
I've tried this
controller
return Redirect::to('/account/'.$id)
->with('alerts',$alerts)
Route
My route : http://localhost:8888/account/1007
View
I tried accessing like this
{!!$alerts!!}
Then, I tried accessing it like this, but I kept getting
Undefined variable: alerts
As per the Laravel documentation on redirects, when redirecting using with() it adds the data to the session, and not as a view variable. Therefore, you will need to access it like:
#foreach (session('alerts') as $alert)
<p>{{ $alert['message'] }}</p>
#endforeach
Try this:
Session::flash('alerts', $alerts);
return route('ROUTENAME', $id);
Just change ROUTENAME, in the name of the route (if defined in routes.php).
For example:
Route::get('account/{id}', ['as' => 'account.show', 'uses' => 'AccountController#show']);
In this example, ROUTENAME would be 'account.show'.
In your view you can access it by doing:
Session::get('alerts');
Info:
- http://laravel.com/docs/5.1/session#flash-data
Sometimes you may wish to store items in the session only for the next request. You may do so using the flash method.
You haven't posted the code that actually loads the view. When you return a Redirect->with(...) all you're doing is passing the variable to the next request. In your controller that serves the account/{id} route you need to return view('viewname', ['alerts' => session('alerts')])
Related
Been trying to find a way to call to pass a multidimensional array to a Post route with no success.
The array looks like this:
"order" => array:16 [
"id" => "1"
"total" => "4825"
"neighborhood" => "Barrio Bravo"
]
"products" => array:2 [
4 => array:4 [
"id" => "4"
"name" => "Maestro Dobel 750ml"
"price" => "530"
"quantity" => "1"
]
1 => array:4 [
"id" => "1"
"name" => "Don Julio 70 700ml"
"price" => "650"
"quantity" => "1"
]
]
"grandTotal" => "1180"
"balanceToPay" => "354"
"cartTotal" => "826"
I don't have any problem asserting the route in the unit test calling the route like so:
$this->post(route('order.success', $orderInfo));
But when it comes to the controller I can't find the way to redirect to order.success with its orderInfo array.
This won't work since redirect only works with GET:
return redirect(route('order.success', $orderInfo));
Ideas?
It's not going to work with a simple redirection because you cannot choose the HTTP method. It's always GET when you make a redirection. It works in your test because you make a POST request manually.
I can see 2 solutions:
You can send data using GET method (they are added as URL parameters). If they are not confidential it can be a solution.
If you don't want to send those data in the URL, you have to save them somewhere and get them from the storage when you're on the order.success page. You can save them, for instance, in the session storage or in the local storage of your browser.
Also, your test isn't good if it tests a behavior that does not happen in your app (post request instead of redirection).
I have a form that submits an array named prazos, and I want to make sure each item is a valid datetime or null. Following the answers to this question and the Laravel docs, I have this in my Controller:
use Illuminate\Support\Facades\Validator;
// ...
$rules = array([
'prazos' => 'required|array',
'prazos.*' => 'nullable|date'
]);
$validator = Validator::make($request->all(), $rules);
$data = $validator->valid()['prazos'];
foreach($data as $id => $prazo) {
// use $data to update my database
// ...
}
The issue is, the validator is not actually stopping invalid content. If I try to submit "loldasxyz" or other gibberish, I get an error from the database. What am I doing wrong?
Note: previously I had been using validators with the syntax $data = $request->validate($rules), but for some reason it didn't work for the array-type data ($data came back empty). I'm not sure if there is some difference in how those different methods work.
Edit: this is what the parameter bag in $request looks like when I test it (the indices are ids, which is why they start at 1):
#parameters: array:3 [▼
"_token" => "Rf6mAp4lqhpZzQRxaxYsees1M0NfrFKpbGe4Hy28"
"_method" => "PUT"
"prazos" => array:5 [▼
1 => "2021-03-22 21:21"
2 => "2021-03-03 11:27"
3 => "jhbkjhg"
4 => null
5 => "2021-03-02 14:21"
]
]
And this is what the validated $data comes out as:
array:5 [▼
1 => "2021-03-22 21:21"
2 => "2021-03-03 11:27"
3 => "jhbkjhg"
4 => null
5 => "2021-03-02 14:21"
]
I wish it would tell me the third value is invalid.
Heres what youre looking for:
https://laravel.com/docs/8.x/validation#rule-date-equals
The field under validation must be equal to the given date. The dates will be passed into the PHP strtotime function in order to be converted into a valid DateTime instance.
I am using pagination in Laravel 5.6 to build an application. I am using Laravel DB instead of Eloquent. However, when I add a pagination link on view, it shows an error Call to a member function links() on array. This is because I am using an array, the default is an object with a collection. The output I am getting looks like
array:12 [▼
"current_page" => 1
"data" => array:3 [▶]
"first_page_url" => "http://127.0.0.1:8000/posts?page=1"
"from" => 1
"last_page" => 3
"last_page_url" => "http://127.0.0.1:8000/posts?page=3"
"next_page_url" => "http://127.0.0.1:8000/posts?page=2"
"path" => "http://127.0.0.1:8000/posts"
"per_page" => 3
"prev_page_url" => null
"to" => 3
"total" => 9
]
When I use normal pagination i.e. without converting to an array, the output is
LengthAwarePaginator {#264 ▼
#total: 9
#lastPage: 3
#items: Collection {#251 ▶}
#perPage: 3
#currentPage: 1
#path: "http://127.0.0.1:8000/posts"
#query: []
#fragment: null
#pageName: "page"
}
The problem I face here is adding other data to collection
I can't use the default output return by pagination() method. Can someone please suggest how to solve this issue?
Using the below, I am getting the required output.
Step 1: Include LengthAwarePaginator in the file
use Illuminate\Pagination\LengthAwarePaginator;
Step 2: Create an object of LengthAwarePaginator
$paginate = new LengthAwarePaginator(Array, countOfArray, perPage, currentPage, [
'path' => request()->url(),
'query' => request()->query()
]);
I kept currentPage value as null.
Return $paginate to view.
return view('home', ['data' => Array, 'page' => $paginate]);
i am building a laravel aplication and i have this line of code which should redirect the user back to form he just submited , with the old input and the result of some operations .
return back()->with(["result" => round($area, 2)])->withInput($request->all());
The problem is that i only receive the old input in blade and the $result variable is not available in the view.
This is how i try to output the result:
<input type="text" name="result" value="{{isset($result)&&old('roofType')==0?$result:''}} ㎡ " class="form-control input-sm" >
And here is what variables i have in the view after submit:
{{ dd(get_defined_vars()['__data']) }}:
array:7 [▼
"__env" => Factory {#89 ▶}
"app" => Application {#3 ▶}
"errors" => ViewErrorBag {#169 ▶}
"roofName" => "Acoperis intr-o apa"
"roofType" => "1"
"roofFolder" => "A1"
"baseFields" => array:3 [▼
0 => "L"
1 => "l"
2 => "H"
]
]
The problem was that I thought that writing
return back()->with('bladeVar', $controllerVar) was the same as return view('test')->with('bladeVar', $controllerVar);,but it wasn't .
You cannot echo a variable using blade normal syntax: {{ $bladeVar }}, Instead, you have to access the session to get the value: {{ session('bladeVar') }}.
After I changed the way I displayed the data all worked as expected.
The answer is you can not.
If you want to use with() then use it with view() like:
return view('welcome')->with(['name' => 'test']);
You can not use with() with back() and redirect(). It won't give you any error but you will not get the variable on the view.
More info: https://laravel.com/docs/master/views#passing-data-to-views
return redirect()->back()->with('result',round($area, 2))->withInput($request->all());
call
{{Session::get('result')}}
in your blade.
return view('profile.reset', compact('user'));
I'm trying to use https://github.com/skmetaly/laravel-twitch-restful-api package to get twitch integration to my website.
That's the error that i get.
ErrorException in helpers.php line 469:
htmlentities() expects parameter 1 to be string, array given (View: /var/www/rafdev.ovh/html/msvixen/resources/views/twitch.blade.php)
My controller
$code = Input::get('code');
if ($code !== null)
{
$token = TwitchApi::requestToken($code);
} else
{
$token = null;
}
$data = TwitchApi::streamsFollowed($token);
return view('twitch', ['token' => $token, 'data' => $data]);
my view
#extends('master')
#section('content')
<h1>Twitch.TV</h1>
{{ $token }}
{{ $data }}
#endsection
After using dd()
array:9 [▼
0 => array:11 [▼
"_id" => 17733016640
"game" => "World of Warcraft"
"viewers" => 15551
"created_at" => "2015-11-15T22:27:13Z"
"video_height" => 1080
"average_fps" => 60.2769481401
"delay" => 0
"is_playlist" => false
"_links" => array:1 [▶]
"preview" => array:4 [▶]
"channel" => array:22 [▶]
]
1 => array:11 [▶]
2 => array:11 [▶]
3 => array:11 [▶]
4 => array:11 [▶]
5 => array:11 [▶]
6 => array:11 [▶]
7 => array:11 [▶]
8 => array:11 [▶]
]
so it works, but when i try to display data - its back to the htmlentities() error
This is happening because $data is returned as an array.
When TwitchApi::streamsFollowed($token); is called, the Facade calls the method in Skmetaly\TwitchApi\Services\TwitchApiService.
This in turn creates an instance of Skmetaly\TwitchApi\API\Users and calls the streamsFollowed() method there.
This method makes a call to /streams/followed which returns a data set such as the example below. It's automatically converted to an array rather than JSON using the Guzzle HTTP Client's json() method.
{
"_links": {
"self": "https://api.twitch.tv/kraken/streams/followed?limit=25&offset=0",
"next": "https://api.twitch.tv/kraken/streams/followed?limit=25&offset=25"
},
"_total": 123,
"streams": [...]
}
In order to display the streams you'd need to iterate over the streams array within $data.
If you were to modify your controller slightly
return view('twitch', ['token' => $token, 'streams' => $data->streams]);
You'd then be able to iterate over the streams in your view.
#foreach($streams as $stream)
{{ $stream }}
#endforeach
Update: You'll notice that each stream is also an array. What this means is you need to choose which of the keys in each array you'd like to display. Let's assume that inside one of the streams there is a key called broadcaster which contains a string; you could modify the above as follows.
#foreach($streams as $stream)
{{ $stream['broadcaster'] }}
#endforeach
Having now read the streams example response documentation it would appear that the contents of a stream varies depending on whether or not the stream is online. NB: This is assuming the data structure is the same as you've not posted the contents of a stream in your question.
This means that offline, {{ $stream['broadcaster'] }} would work, but when online it wouldn't and you'd get the same error. What you'll likely need to do is use an #if #else block in your #foreach to determine if the stream is null before trying to echo part of the information.
You could also filter the offline streams in the controller by removing null values from data.