Laravel : How to add particular array store in session - laravel

I am little confused about session as i am new to in laravel. On my laravel app there is a lists of activity, every activity has it's details. When i click on activity button(button name: interesed?) activity id add on session, If i add another activity it is also add on session. I need functionality to add and remove inquiry id from session & on last i want all added activity id.
Note: I am doing using ajax.
What i have done sharing here.
Here is a view of my lists inquiry
On my web.php define a route
Route::get('addInquiryData','Front\PlanController#addInquiry')->name('addInquiryData');
On view view.blade define onclick function
onclick="addInquiry({{ $activity->id }})"
On my ajax call
function addInquiry(id) {
var activity_id = id;
if(activity_id)
{
$.ajax({
type:"GET",
url:"{{ route('addInquiryData') }}?activity_id="+activity_id,
success:function(res)
{
if(res)
{
// operation here
}
}
});
}
}
On my controller just define a function.
public function addInquiry(Request $request) {
dd($request->activity_id); // gt activity id here
}
How can i do this?

You may try this code
Store Your Activity Id value in variable
$activityId=$request->activity_id
You can add value in session like this
if(!Session::has('activity_'.$activityId)){
session(['activity_'.$activityId=>$activityId]);
}else{
session()->forget('activity_'.$activityId);
}
You can remove value in session like this
session()->forget('activity_'.$activityId);

Related

change prop based on parameter

In my app (Laravel + InertiaJS + Vue3), I want to refresh some client-side JS variables based on a client-side parameter:
Client has a table of events, each one holding a button with its corresponding event_id.
When pressed, the server receives a request and performs some calculations (dynamically generates an external URL and some parameters). Nothing is persisted to the database.
Hopefully, the generated URL and the parameters are sent-back to the client, and the user is then redirected there (client-side) using a POST form (that is why I can not redirect directly from the server).
What is the best way to do that?
This is what I have so far:
// In my controller
...
public function __construct()
{
$this->generator = new URLGenerator();
}
public function generate(Event $event)
{
$url = $this->generator->getURL($event);
return redirect()->back();
}
// My controller
public function index()
{
return Inertia::render('Events', [
'events' => fn () => new EventResource(
auth()->user()->events
)
]);
}
I need to somehow inject the $url variable back to Vue.
Thanks in advance for any help.

vue axios delete request not working in laravel 7

Vue component
methods: {
removeCategory(index) {
if (confirm('Are you sure ?')) {
let id = this.categories[index].id;
console.log("ID="+id);
if (id > 0) {
axios.delete('/api/categories/' + id);
}
this.categories.splice(index, 1);
}
},
Routes Api
Route::delete('/categories/{category}', 'CategoryController#destroy');
Controller
public function destroy(Category $category)
{
$this->authorize('delete', $category);
$category->delete();
return $category;
}
Put request is working fine for inserting and updating data, but DELETE request is not able to delete data from the database.
Thanks
Laravel check CSRF token.
You need to add X-CSRF-TOKEN in the request header
You can read this doc : https://laravel.com/docs/7.x/csrf#csrf-x-csrf-token
If you haven't found the answer yet, quick fix as:
Remove the model binding in your Controller.
Grab specific category with an id.
Authorize and delete it.
(no need to modify the Component and the Route)

Dynamic data load by ajax in laravel

I have Post show method where i show each post by their id and this is how it's look like:
$post = Post::find($id);
$comments = Comment::where('post_id', '=', $post->id)->get();
return view('single', compact('post','comments'));
with this i can basically load my post details and foreach that post comments (so far so good).
What I want to do
Is to get my comments by ajax, so for example when user 1 is reading the post and somewhere else user 2 add new comment user 1 see it imminently. So user 1 doesn't need to refresh the page to see the new comment.
Question
How can I do that?
You can use channels of Laravel combined to redis server. Each time you store a comment you can push to the post channel your comment and display it with ajax (use laravel echo server). All subscribed users to this channel will receive the new comment.
This is how I would do this
PHP
Route::get('/posts/{post}/comments', 'PostsController#comments');
public function post(Post $post) {
return response()->json(
Post::with('comments')->get() // Create HasMany relation named "comments", see Eloquent Relationships
);
}
Javascript
(function($) {
var intervalMiliseconds = 5000;
var pool = function() {
$.ajax({
method: 'GET',
url: '/post/100/comments',
success: function(response) {
console.log(response);
}
});
};
setInterval(pool, intervalMiliseconds);
})(jQuery);
Please avoid using PHP code in your javascript code, simply move all JS code to *.js files, and most if not all the required data from PHP pass by using data-* element attributes

Update Ember model live via action

I'm new to Ember.js and keep struggling on a simple task. My goal is to achieve live update of the page content after action is triggered. I'm quite lost in Ember logics regarding route-controller-model relationship in this case.
So my template.hbs is something like:
<h1>{{model.somedata}}</h1>
<button {{action 'getContent'}}>Get Content</button>
My controller accepts some params from user form and makes the AJAX call:
export default Ember.Controller.extend({
somedata: 'hello',
actions: {
getContent: function () {
var self = this;
Ember.$.ajax({
// ... standart call with some query data
success: function(result) {
self.set('somedata', result);
}
});
}
}
});
My route model returns only controller params, so if I get it right as controller properties get updated, there must be a simple step to update the current model and display all changes to the template.
export default Ember.Route.extend({
model: function(params) {
return params;
}
});
Can you guys give me a tip how this process is regularly built in Ember?
You are looking for self.set('model.somedata', results).
Your code as it stands is setting the somedata property on the controller, which doesn't affect anything.
Yeah it's a bit confusing, here's how I think of it...
First Ember sets up the route.
The route has multiple hooks that are used to get and process the model (i.e. beforeModel, model, afterModel). Ember will always look for these as part of it's opinionated nature.
There is also a setupController hook that will fire after all the model hooks. As part of the setupController hook, the controller will be created and the model will be passed to the controller.
Once that happens, I've found it helpful to think of the model as no longer being part of the route, but the controller instead.
Controllers will be deprecated. So IMO do not use controllers.
Handle that action in your route. If you bind value to the object returned by model hook, your data and page will be updated when you update the value.
export default Ember.Route.extend({
somedata: null,
model: function(params) {
return {
params: params,
somedata: this.get('somedata')
};
},
actions: {
getContent: function () {
...
var _this = this;
...
success: function(result) {
_this.set('somedata', result);
}
}
}
});

Laravel 4 how to listen to a model event?

I want to have an event listener binding with a model event updating.
For instance, after a post is updated, there's an alert notifying the updated post title, how to write an event listener to have the notifying (with the post title value passing to the listener?
This post:
http://driesvints.com/blog/using-laravel-4-model-events/
Shows you how to set up event listeners using the "boot()" static function inside the model:
class Post extends eloquent {
public static function boot()
{
parent::boot();
static::creating(function($post)
{
$post->created_by = Auth::user()->id;
$post->updated_by = Auth::user()->id;
});
static::updating(function($post)
{
$post->updated_by = Auth::user()->id;
});
}
}
The list of events that #phill-sparks shared in his answer can be applied to individual modules.
The documentation briefly mentions Model Events. They've all got a helper function on the model so you don't need to know how they're constructed.
Eloquent models fire several events, allowing you to hook into various points in the model's lifecycle using the following methods: creating, created, updating, updated, saving, saved, deleting, deleted. If false is returned from the creating, updating, saving or deleting events, the action will be cancelled.
Project::creating(function($project) { }); // *
Project::created(function($project) { });
Project::updating(function($project) { }); // *
Project::updated(function($project) { });
Project::saving(function($project) { }); // *
Project::saved(function($project) { });
Project::deleting(function($project) { }); // *
Project::deleted(function($project) { });
If you return false from the functions marked * then they will cancel the operation.
For more detail, you can look through Illuminate/Database/Eloquent/Model and you will find all the events in there, look for uses of static::registerModelEvent and $this->fireModelEvent.
Events on Eloquent models are structured as eloquent.{$event}: {$class} and pass the model instance as a parameter.
I got stuck on this because I assumed subscribing to default model events like Event:listen('user.created',function($user) would have worked (as I said in a comment). So far I've seen these options work in the example of the default model user created event:
//This will work in general, but not in the start.php file
User::created(function($user)....
//this will work in the start.php file
Event::listen('eloquent.created: User', function($user)....
Event::listen('eloquent.created: ModelName', function(ModelName $model) {
//...
})

Resources