Laravel - Getting string from a flash - laravel-4

After processing form input, I redirect to a new route with some flash data:
return Redirect::route('work.index')
->with('flash', 'New work entry has been entered');
In the controller specified by work.index, I try to access the data
$flashed = Session:get('flash');
However, instead of a string, I end up with an array with two sub-arrays, old and new
Am I doing something wrong? Am I supposed to do this?
$flashed = Session::get('flash')['new'][0]

Store Data for next request
Session::flash('city', 'New work entry has been entered');
Retrieve Data from last request
$data = Session::get('city');
return Redirect::route('work.index')
->with('data', $data);

My Advice is to use Laracasts/Flash package that helps you to manage Flash messages in an easy way.
Here the GitHub repo: https://github.com/laracasts/flash
Installation
First, pull in the package through Composer.
"require": {
"laracasts/flash": "~1.0"
}
And then, if using Laravel, include the service provider within app/config/app.php.
'providers' => [
'Laracasts\Flash\FlashServiceProvider'
];
And, for convenience, add a facade alias to this same file at the bottom:
'aliases' => [
'Flash' => 'Laracasts\Flash\Flash'
];
And you can use it with:
Flash::info('Message')
Flash::success('Message')
Flash::error('Message')
Flash::warning('Message')
Flash::overlay('Modal Message', 'Modal Title')
Now in your theme you can easly integrate it with:
#include('flash::message')
NB:
Note that this package is optimized for use with Twitter Bootstrap.

Related

Dynamic route url change is not reflecting in laravel package

I am creating a package which gives a config file to customize the route url which it will add, I can see config file values in the controller, but same config('app_settings.url') is coming as null in
pakacge/src/routes/web.php
Route::get(config('app_settings.url'), 'SomeController')
my tests are also giving 404 and app_settings config change is not getting picked by route.
function it_can_change_route_url_by_config() {
// this should be default url
$this->get('settings')
->assertStatus(200);
// change the route url
config()->set('app_settings.url', '/app_settings');
$this->get('app_settings')
->assertStatus(200);
$this->get('settings')
->assertStatus(400);
}
app_setting.php
return [
'url' => 'settings',
'middleware' => []
];
It works when I use this package, but tests fail.
Please help How I can give the option to change the route url from config.
To be honest I think it's impossible to make such test. I've tried using some "hacky" solutions but also failed.
The problem is, when you start such test, all routes are already loaded, so changing value in config doesn't affect current routes.
EDIT
As alternative solution, to make it a bit testable, in config I would use:
<?php
return [
'url' => env('APP_SETTING_URL', 'settings'),
'middleware' => []
];
Then in phpunit.xml you can set:
<env name="APP_SETTING_URL" value="dummy-url"/>
As you see I set here completely dummy url to make sure this custom url will be later used and then test could look like this:
/** #test */
function it_works_fine_with_custom_url()
{
$this->get('dummy-url')
->assertStatus(200);
$this->get('settings')
->assertStatus(404);
}
Probably it doesn't test everything but it's hard to believe that someone would use dummy-url in routing, and using custom env in phpunit.xml give you some sort of confidence only custom url is working fine;

Mailchimp package not adding email address to list

I am using the following laravel package for my newsletters:
laravel-newsletter.
I have the following code in my newsletterController.php:
public function index() {
Newsletter::subscribe('rincewind#discworld.com', ['FNAME'=>'Goti', 'LNAME'=>'Loki'], 'test');
return 'Ola !';
}
Now when i go to: /newsletter in my application i see Ola !, but when i open my mailchimp dashboard i see don't see rincewind#discworld.com added to the list of emails for the list test.
I also tried the following method of the mailchimp package:
return Newsletter::isSubscribed('codedevakagautam#gmail.com');
This email address already exists in the list test, i get the following error:
Call to undefined method Spatie\Newsletter\Newsletter::isSubscribed()
What am i doing wrong ? Can somebody please guide me.
Please, verify if you have added an entry to the providers array at your config/app.php
// config/app.php
'providers' => [
...
Spatie\Newsletter\NewsletterServiceProvider::class,
...
];
And at aliases array on the same file
// config/app.php
'aliases' => [
..
'Newsletter' => Spatie\Newsletter\NewsletterFacade::class,
];
Also, you need to import the package on your controller. By doing:
use Newsletter;
Be sure to import this way.
If you did all of the steps above, now you can try to use the method:
return Newsletter::isSubscribed('codedevakagautam#gmail.com');
And to subscribe users to a list, you need to send a 'status' parameter.
The possible values for this field is:
subscribed
unsubscribed
cleaned
pending
See the docs here:
http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/
If this does not work for you, you can have a look at this package:
https://github.com/drewm/mailchimp-api

laravel api with vue 2 js not returning data - could 'localhost:8000' (or '127.0.0.1:8000') be the issue?

I am using the repo https://github.com/mschwarzmueller/laravel-ng2-vue/tree/03-vue-frontend so I have 100% confidence in the reliability of the code. I can post through the laravel api endpoint through the very simple Vue client, and also through Postman. Through Postman I can retrieve the table data array, but not so in the client app. In POSTMAN:
localhost:8000/api/quotes
works just fine.
IN THE vue 2 js CLIENT APP:
methods: {
onGetQuotes() {
axios.get('http://localhost:8000/api/quotes')
.then(
response => {
this.quotes = (response.data.quotes);
}
)
.catch(
error => console.log(error)
);
}
returns nothing. returning the response to Console.log returns nothing. The Network/XHR tab shows the table data rows, but I am not sure what that means.
I know for sure that this code works for others with their unique api endpoints, which I assume may not use localhost or '127:0.0.1:1080.
Edit: in response to request for more info
public function getQuotes()
{
$quotes = Quote::all();
$response = [$quotes];
return response()->json($response, 200);
}
and the relevant route:
Route::get('/quotes', [
'uses' => 'QuoteController#getQuotes'
]);
Just to confirm: I am using verified github repo code in which the ONLY change is my api endpoint addressas mentioned in the first line of the body of this question. . Note that the Laravel back end is also derived from a related repo in Max's fine tutorial. The running code can be seen at
So I really don't think this is a coding error- but is it a configuration error due to me using local host??
EDIT: It WAS a coding error in the laravel controller as shown below
The reason your code isn't working if because you haven't provided a key for your $quotes in your controller but you're looking for it in your vue file (response.data.quotes).
[$quotes] is essentially [0 => $quotes] so when the json response comes through it be 0: [...] not quotes: [...].
To get this to work you just need to change:
$response = [$quotes];
to:
$response = ['quotes' => $quotes];
Furthermore, just an FYI, you don't need to provide the 200 in response->json() as it's the default and you can just return an array and Laravel automatically return the correct json response e.g.:
public function getQuotes()
{
$quotes = \App\Models\Artist::all();
return compact('quotes'); //<-- This is just another way of writting ['quotes' => $quotes]
}
Obviously, you don't have to if you don't want to.
Hope this helps!

Pass variable from middleware to view via controller in Laravel 5.2

Hi I am trying to do the following in Laravel 5.2.
Summary: Pass some variables from middleware to view, via controller
Detailed: When a client is logged in, no matter what route they want, we need to check if they have completed all "setup steps" (each step refers to a different route, e.g. one could be company info, another could be product settings, etc). If they have completed all setup steps, then let them proceed to their chosen route, otherwise we redirect to the appropriate "setup steps" route, whichever one they haven't completed yet.
All client controllers run the same middleware, called NonSuperAdmin. I would like to put the checking of "setup steps" in this middleware, and redirect from there as appropriate. If client is redirected to a setup route by this middleware, we need the "incompleteSetupTasks" collection to be passed on to the relevant view, via the appropriate setup steps controller method.
Is this possible? Any help is much appreciated.
In the middleware use session handler
if($condition === true){
$data = [ //your content ];
Session::flash('your_key', $data);
}
next($request);
This data will also be available in your controller and in view
This is how you can access data in controller
public function yourControllerAction($request)
{
$somevariable = Session::get('your_key');
$viewdata = [
'content' => $somevariable
]
return view('yourview', $viewdata);
}
Or directly access the session data in view
//inblade
<p>
Your html content
#foreach(Session::get('your_key' as $data)
//your stuff
#endif
</p>
May be use Laravel Session to store and read values?
You can pass your setup steps to get or post parameters and check in routes with middleware if these parameters are empty:
Route::get('post/{setup1?}/{setup2?}', ['middleware' => 'role:admin', function ($setup1, $setup2) {
if(empty($setup1) and empty($setup2)){
// do smth
} else {
// redirect
}
}]);
Question marks mean, that they are optional parameters. Hope it was helpful.

Datatable server side php class for laravel

I want my datatables to process the data on the server side, I am referencing this example.
Server Side Example
However, the server side php class "ssp.class.php" given in this example uses core php with raw sql, I can not use it directly for laravel projects. Does anyone has reference to laravel way doing datatables. I don't want to use any packages at the moment though.
UPDATED 31/01/2023
You can use syamsoul/laravel-datatable-two-ssp package..
Link here
Open CLI and enter your app directory
Run this command composer require syamsoul/laravel-datatable-two-ssp
In your controller, need to add use SoulDoit\DataTableTwo\SSP;, and you can follow the code below:
private function dtColumns()
{
return [
['label'=>'ID', 'db'=>'id', 'formatter'=>function($value){
return str_pad($value, 8, '0', STR_PAD_LEFT);
}],
['label'=>'Email', 'db'=>'email' ],
['label'=>'Username', 'db'=>'username' ],
['label'=>'Created At', 'db'=>'created_at' ],
];
}
private function dtQuery($selected_columns)
{
return \App\Models\User::select($selected_columns);
}
This is working perfectly on Laravel 8 and above.
.
.
Below is my old answer.. (21 March 2019)
You can use syamsoul/laravel-datatable-ssp package..
Link here
Open CLI and enter your app directory
Run this command composer require syamsoul/laravel-datatable-ssp
In your controller, need to add use SoulDoit\DataTable\SSP;, and you can follow the code below:
public function get(){
$dt = [
['db'=>'id', 'dt'=>0, 'formatter'=>function($value, $model){ return str_pad($value, 8, '0', STR_PAD_LEFT); }],
['db'=>'email', 'dt'=>1],
['db'=>'first_name', 'dt'=>2, 'formatter'=>function($value, $model){ return $value . ' ' . $model->last_name; }],
['db'=>'created_at', 'dt'=>3],
['db'=>'email_verified_at'],
['db'=>'last_name'], // must include this because need to re-use in 'first_name' formatter
];
$dt_obj = new SSP('\App\User', $dt);
$dt_arr = $dt_obj->getDtArr();
return response()->json($dt_arr);
}
This is working perfectly on Laravel 5.8 ... I'm not sure about the other versions.

Resources