How to handle json request in laravel controller? - laravel

I'm using JSON request to get nation detail in my view, here is how I am doing it;
Controller:
public function ajaxrequest(Request $request)
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations);
}
now I want to access data from Area table, I will have to create another controller? or I can add that in the above controller? I have 10 different tables like nation from where I want to get data through JSON. but I am not sure whether I can do everything in a single controller.

It all depends how do you want to access data and yes you can fetch data from one controller only if it's needed.
Also you can check it based on the request
EXAMPLE :
public function ajaxrequest(Request $request)
{
$check = $request->get('something_to_check");
if($check){
$data = Table1::all()->pluck('id');
}else{
$data = Table2::all()->pluck('id');
}
return response()->json([
'data' => $data,
//...
]);
}

Like #ViperTecPro mentioned, you can access multiple tables from the same method in a controller but if possible you should have separate endpoints for each case to you get rid of multiple if checks.
Just a thought.

Related

How to update multiple Rows In Laravel Controller

basically I want to update this table in one go or bulk update.
I wanted to update the "image_id" field on this table.
This is my code in the Controller
public function storebulk(Request $request,$id)
{
$ids= ['8','9','10']; //sent from the front-end
$barcode = Barcode::where('id', $ids)->update(['image_id'=>$id]);
return 'Done';
}
but for some reason it doesn't work. if anyone can point out what I missed here it will be great.
thanks
You should use whereIn:
public function storebulk(Request $request, $id)
{
$ids= ['8','9','10']; //sent from the front-end
$barcode = Barcode::whereIn('id', $ids)->update(['image_id'=>$id]);
return 'Done';
}
In Laravel, If you want to update multiple rows or get multiple rows of same type always use whereIn.
The Docs Define whereIn as -
The whereIn method verifies that a given column's value is contained within the given array
public function storebulk(Request $request,$id)
{
$ids= ['8','9','10']; //sent from the front-end
$barcode = Barcode::whereIn('id', $ids)->update(['image_id'=>$id]);
return 'Done';
}
Link to docs

How can add additional Attribute in my JSON response with dynamic value in laravel

In my app i have a Posts and a Reacts table both are connected with relationship.
In App user can react to a post(like or dislike) and for retrieve this i'm using this function :
public function feed()
{
$posts=Post::with('user')
->with('reacts')
->withCount('comments')
->orderBy('created_at', 'DESC')
->get();
return response()->json(["posts" => $posts]);
}
the response is:
i want to add one more field in Posts Object for isUserLiked and if the current authenticated user liked the post then value will be true or false for him something like this:
i can add a additional field but how can i set the value dynamically for that
this is what i am doing in my Post Model:
protected $appends = ['isUserLiked'];
public function getIsUserLikedAttribute($id)
{
$react=React::where('user_id',auth()->user()->id)->where('post_id',$id)->exists();
return $react;
}
this is returning false because i don't know any way to pass the arguments(Post id).
is there any better way i can get the desired response? Thanks!
public function getIsUserLikedAttribute($id)
{
return React::where('user_id',auth()->user()->id)->where('post_id',$this->id)->exists();
}
In your user model:
public function reacts(){
return $this->hasMany(React::class);
}
public function scopeReactOnPost($query, $post_id){
return $this->reacts()->where(function($query) use ($post_id){
$query->where('post_id',$post_id);
});
}
and in your controller:
$user->reactOnPost($post_id)->first();
or
$user->reactOnPost($post_id)->get()->count();
Will let you know if user had any reaction on the specified post.
and for adding this to your json output you can artisan make a resource for your post model. Laravel Resources

save collection in global variable in laravel 5.6

so basically i have an index page where i have to go to controller to fetch data from database
route:-
route::get('/index/{$x}', 'indexController#index');
index controller:-
$data = Data::where('name', $x)->get();
return View::make('index', compact('data');
then inside index page i have link that goes to second page
with same data, i d not want to query the same data as it may affect performance
route:-
route::get('/second', indexController#second);});
Second Controller:-
$data = $data->sortBy('id');
return View::make('second', compact('data');
i thought of saving data in global variable in controller
so i added private variable inside controller and try to access it through $this->data
but it did not work cause based on my search the controller will be closed after it returns view
so if i try access $this->data inside second function it will be empty
is it possible to save queried data (collection) in global variable
as i do not want to query same data for every page
your help will be appreciated
If you having same data on different pages that will not be solved using any kind of global variables. You need to cache query results. Please check cache in laravel docs https://laravel.com/docs/5.6/cache
Here is how that is usually done:
$data = Cache::get('some_cache_key');
if (empty($data)) {
$data = Data::where('name', $x)->get();
Cache::put('some_cache_key', $data, 60); //60 minutes
}
return View::make('index', compact('data');
There are multiple ways to achieve this. Either you can store the data in the Session and access all across the application
$data = Data::where('name', $x)->get();
session()->put('data', $data);
You can also use View::share('key', $data)
In your AppServiceProvider inside boot() method
public function boot()
{
View::share('data', Cache::get('data'));
}
In your controller.
$data = Data::where('name', $x)->get();
Cache::put('data', $data);
By this way you can access the data all across the application using {{ $data }} in your views.
hope this helps.

Returning custom variable in Settings - Laravel Spark

I have setup Spark and I have created my custom view in Settings - Students (assume User object is actually a teacher). I have also created migration and model Student.
Now http://spark.app/settings/students returns the page successfully. At this point, I need to return data from backend. I investigated Spark\Http\Controllers\Settings\DashboardController#show - which is the method returning the 'settings' view, however this doesn't return any data to view using ->with('user', $user)
But, as mentioned in Docs, :user="user" :teams="teams" :current-team="currentTeam" already available out of the box.
Where and how does Spark returns these values to /settings? And How do I make my Student object available likewise?
Now, if I want to return my Student object to front-end, I have 2 choices.
1) edit Spark\Http\Controllers\Settings\DashboardController
2) I think Spark\InitialFrontendState is the place where Spark returns these objects user, teams, currentTeam. This approach is something I've seen for the first time to be honest and I didn't really understand how it works.
So how should I achieve in Spark, something as simple as :
return view('spark::settings')->with('student', $student); ?
Add a new route and set up your own Controller & own view
web.php
Route::get('/settings/students', 'SettingsStudentController#index');
SettingsStudentController.php
class SettingsStudentController extends Controller {
public function __construct() {
$this->middleware('auth');
}
public function index(Request $request) {
$user = Auth::user();
$student = STUDENTCLASS::whatever();
return view('yourstudentview', ['student' => $student , 'user' => $user]);
}
}

Laravel 5.4 storing mass assignment model and relationship

I'm unsure of the best practice when inserting mass assignment relationships within Laravel 5.4 - I'm new to the framework. The below code is working correctly, however can you tell me is there a way to simply into one line (inserting relationships)?
I've tried to look at 'save()'and 'push()' but it's not working as expected. Would this have an impact if transactions would scale up?
I have a Listing model, with a hasOne relationship:
public function garage()
{
return $this->hasOne('App\Garage', 'post_id');
}
First of all I have some validation, then I use the following to store, which I want to simplify to one one line of code:
public function store(Request $request)
{
// Validation has passed, insert data into database
$listing = Listing::create($request->all());
$listing->Garage()->create($request->all());
}
Also if I wanted to return the data inserted, how would I do this as the following is only returning the Listing model and not the Garage relationship? Yes I know that I wouldn't do this in a real world application.
return \Response::json([
'message' => 'Post Created Succesfully',
'data' => $listing
]);
Any help is muchly appreciated
Method chaining
Your store method looks good. You could chain methods though, if you don't need the listing object itself:
public function store(Request $request)
{
// Validation has passed, insert data into database
$garage = Listing::create($request->all())
->garage()->create($request->all();
}
But if you need the listing object, it's fine as you did it before!
Returning relation models
If you want to return the garage relation model too, you can simply do that by accessing it like a normal class propery:
return \Response::json([
'message' => 'Post Created Succesfully',
'data' => [$listing, $listing->garage]
//Access collection of garage relation ship
]);

Resources