I am trying to send multiple cookies with one response. I have an array with cookies named
$cookies
What would be an alternative of the following example if I have an array with values instead of specific values
return $response
->withCookie(cookie()->forever('region', $region))
->withCookie(cookie()->forever('somethingElse', $somethingElse));
I have tried the following code but it does not seem to work.
$response = $this->response(200, 'Successful');
foreach($cookies as $cookie){
$response = $response->withCookie($cookie);
}
return $response;
Just save the cookies via the Cookie::queue() method.
Then you can access the cookies anywhere via the Cookie::get() method afterwards.
You won't need to add them to the response if you do it this way, and they will still be accessible inside of views etc.
Try adding this function inside "vendor\laravel\framework\src\Illuminate\Http\Response.php". The function adds and removes multiple cookies in one response.
/**
* Add cookies to the response.
*
* #param Array of $cookie
* #return \Illuminate\Http\Response
*/
public function withCookies(Array $cookies)
{
foreach($cookies as $cookie)
$this->headers->setCookie($cookie);
return $this;
}
Related
I am using Laravel and pusher. Pusher is working good. But I want to know how can I get data when I will insert new data into database?
Process is if someone push/insert data on the table, then those data will automatically show without reloading the page.
Can anyone explain it? or give me any documentation or video link about it?
What you need are Broadcast Events.
Let's assume that you are inserting a Post and you want all users to get notified about a new post, therefore refresh the posts table index.
All your users should be subscribed to a presence channel, but you could use private or public channel. IMO, presence channel works better for this scenario since you are dispatching just 1 event for all users instead of 1 event per user in case of private channel
In your store function in PostController.php you dispatch the event once Post has been created:
use App\Events\PostCreated;
public function store(Request $request)
{
// Insert new post
$post = Post::create($request->all());
// Dispatch broadcast
PostCreated::dispatch($post);
return $result;
}
Then in your PostCreated.php Event, you send the post itself as the event payload:
<?php
namespace App\Events;
use App\Models\Post;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PostCreated implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $afterCommit = true;
public Post $post;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Post $post)
{
$this->post = $post;
}
/**
* The event's broadcast name.
*
* #return string
*/
public function broadcastAs()
{
return 'post.created';
}
/**
* Get the data to broadcast.
*
* #return array
*/
public function broadcastWith()
{
return $this->post;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('posts');
}
}
Now you need that all users subscribe to the right channel. Assuming, again, that you are using laravel echo, this is how I do it within a Vue Js app by joining a presence channel posts and listening for post.created event.
this.echoInstance.join('posts')
.listen('.post.created', (post) => {
// Do something like refresh table
// or insert `post` object directly in posts array
})
Since you didn't provide any code, this is a generic sample. Next time, please share what you've done so far.
I'm in new coding I clone this https://github.com/cretueusebiu/laravel-vue-spa laravel template to create a new project I'm created another table to store articles and this is my controller. this not returns any data from database please help me.
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return Article::orderBy('id', 'DESC')->get();
}
Your problem is your route definition:
Route::resource('/article', 'ArticleController');
That needs to be:
Route::resource('article', 'ArticleController');
No leading slash.
When you use Route::resource you are in fact defining routes for GET, POST, PUT, PATCH, and DELETE. It's directly related to your model Article.
Update
Change web.php to this:
Route::resource('article', 'ArticleController');
// this is always the last route in the file
Route::get('{path}', function () {
return view('index');
})->where('path', '(.*)');
I have a controller that is purely for API use (no view or layout).
I want every action to return JSON format and have the Content-Type in the response be application/json.
I could achieve the header part by using the controller postDispatch() but couldn't find a way to do json_encode() from single place (I know I can do it from every action however I wanted it to be centralized).
I have even tried to use a plugin and there to manipulate the request body but for some reason that is not clear to me it is always empty.
Currently my solution is as follows:
public function init()
{
// no Layout
$this->_helper->layout()->disableLayout();
// no views
$this->_helper->viewRenderer->setNoRender(true);
}
public function indexAction()
{
$data = array("likes","to","sleep");
echo Zend_Json::encode($data);
}
public function postDispatch()
{
$this->getResponse()->setHeader('Content-Type', 'application/json');
}
Now, if i only managed to do the echo Zend_Json::encode in one single place...
You can use the ContextSwitch action helper
The JSON context sets the 'Content-Type' response header to 'application/json', and the view script suffix to 'json.phtml'. By default, however, no view script is required. It will simply serialize all view variables, and emit the JSON response immediately.
You will need to register it within the controller.
class FooController extends \Zend_Controller_Action
{
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'json')
->addActionContext('bar', 'json')
->initContext('json'); // json arg here means that we only allow json
}
}
You would then need to pass the format parameter in the url /module/foo/bar/format/json or as a query parameter ?format=json
You can create your own controller plugin.
In preDispatch turn off layout and view renderer and in postDispatch set content-type header in response.
Next option is to assing data to view.
public function indexAction() {
$data = array("likes","to","sleep");
$this->view->assign('data', $data);
}
and in view script call json view helper <?php echo $this->json($this->data); and do not use layout.
I have a little problem, I'm trying to send a json response, but all I get is a empty object all the time.
So here is my code:
//Get the data from DB
$template = $this->getDoctrine()
->getRepository('EVRYgroBundle:Template')
->findOneBy(
array('active' => 1)
);
if (!$template) {
throw $this->createNotFoundException(
'No product found for id '
);
}
//Send the response
$response = new Response();
$response->setContent(json_encode($template));
return $response;
And when I'm viewing it all it shows is {}
And I have also tried with the jsonResponse and with this code:
$response = new JsonResponse();
$response->setData($template);
And I have no idea what i'm doing wrong!
json_encode expects an array as first parameter to be given in. When you call it with an object the public properties will may be displayed. To keep the properties protected (as they should be) you can add a expose function to your entity:
/**
* delivers all properties and values of the entity easily
*
* #return array
*/
public function expose()
{
return get_object_vars($this);
}
and then call
$response->setData(json_encode($template->expose()));
This way you keep your entity clean with only access via getter and setter methods and you can access all properties via json still.
Well I found the problem, the problem was that some variables that holds the information from the db was set to protected and not public.
I would like to use MongoDB to store the logs of my json api. I am using the Doctrine 2 ODM.
Reading through the manual I understand that to store my json api response, I should use the #Field annotation with some well chosen data type. However, I do not find the one that would fit the BSON data type.
Is there any data type that will allow me to get things working with something like
$myRecord->setResponse($json_response);
and later on perform MongoDB queries like
db.Logs.find({"response.user": "foo"});
? What is the correct way to deal with this ?
After a few tries, here I am: the correct type to do this is the Hash type. Our document has a response field that looks like this:
/**
* #MongoDB\Hash
*/
protected $response;
And the call to set the value is as follow:
$myRecord->setResponse(json_decode($result, true));
This is it!
Edit: As I had some issues to retrieve the stored values, I came to use mongodb callbacks :/
/**
* (...)
* #MongoDB\HasLifecycleCallbacks
*/
class Log
{
(...)
/** #MongoDB\PreLoad */
public function preLoad(array &$data)
{
$data["response"] = json_encode($data["response"]);
}
/** #MongoDB\PrePersist */
public function prePersist()
{
$a_json = json_decode($this->getResponse(), true);
$this->setResponse($a_json);
}
Which makes the set call straight, by the way:
$myRecord->setResponse($result);