How to query db by uri id in laravel through user auth? - php

I'm just finished the intermediate laravel tutorial here: https://laravel.com/docs/5.2/quickstart-intermediate and am trying to push on a bit.
While I can fetch all the tasks via auth'd user id with:
public function index(Request $request)
{
$tasks = $request->user()->tasks()->get();
return view('tasks', [
'tasks' => $tasks,
]);
}
I want to create a view function... how, if I create a link to /task/7 to I query the info about the task with id 7 (for example) & send it to the view?

Define a route to match that /task/7 URL like so:
Route::get("/task/{taskId}", "TaskController#getView");
Then, in your TaskController, define getView function as:
public function getView($taskId){
$task = \App\Task::where("id", "=", $taskId)->first();
return view("tasks.view")->with(["task" => $task]);
}
This is the simplest way to pass a taskId to via a URL parameter, query your DB for the matching record and return a view to display information about it.
There's more involved, like validating the record exists for example, but this should get you on your way.

Related

Laravel store() method from api controller not returning updated data

I'm having an issue where the store method in my UserCountries API controller is returning data that seems to be one step behind and I'm not sure why. My app has two models: Country and User, which have a many-to-many relationship with a pivot table. In my app a particular user should be able to 'like' and 'unlike' a country.
This mostly works as expected, however my issue is that the data returned on each request is one step behind - e.g., if I send a POST request to like a particular country, I get a 200 response but I am returned a UserCountriesResource which does not include that country that should have just been added. If I then immeditaely send a GET request, it returns a UserCountriesResource which does include that country. Can anyone help me figure out why?
Here are my routes:
Route::group(["prefix" => "me/countries"], function(){
Route::get("", [UserCountries::class, "index"]); // see all countries liked by user
Route::post("", [UserCountries::class, "store"]); // add or remove country from user
});
My index method in the UserCountries controller is below:
public function index()
{
return CountryResource::collection(auth()->user()->countries);
}
My store method in the UserCountries controller is below:
public function store(UserCountriesRequest $request)
{
$user = auth()->user();
$user->setCountries($request->get("countries"));
return new UserCountriesResource($user);
}
The store method calls the setCountries method in the User model:
public function setCountries(array $strings) : User
{
$countries = Country::fromStrings($strings);
$countries->map(function($country) use($countries){
if($this->countries->contains($country)){
Country::find($country->id)->users()->detach($this->id);
} else {
$this->countries()->syncWithoutDetaching($country->id);
}
});
return $this;
}
The setCountries method above in turn calls the fromStrings method in the Country model:
public static function fromStrings(array $strings) : Collection
{
return collect($strings)->map(fn($str) => trim($str))
->unique()
->map(fn($str) => Country::firstOrCreate(["NAME"=>$str]));
}
Do let me know if there's anything else I can add to make this more helpful!
You are loading the relationship before you are adding/removing any of the related records. That loaded relationship, Collection, won't include these changes. You will need to reload the relationship to get the new list of related records.
I don't know the rest of your code but you would add a call like this, if this was the case:
$user->load('countries');
This is loading the relationship (if it wasn't already loaded):
if($this->countries->contains($country))

show data if you have user id - laravel

I am creating a data list and I print it with foreach, i would like it to display the data only if user_id matches the user_id reading the data. (previously I already have the user authentication created)
I want the users who enter to only see the data that contains their user_id.
I already made the relationship between the users table 'id' field with user_id
pass the data with:
public function index()
{
$servicios = App\Servicio::all();
return view('home', compact('servicios'));
}
How do I show the data that corresponds to the user_id of each one without others seeing their data??
You could set up a relationship inside the User.php model.
public function servicios() {
return $this->hasMany(Servicio::class);
}
Then in your controller:
public function index()
{
$servicios = auth()->user()->servicios;
return view('home', compact('servicios'));
}
You can get the user's list of services easily using Auth::user(), example:
User::with(['servicios'])->find(Auth::id());
you should get the user from your request, then filter by its id ...
public function index()
{
$user_id=app('request')->user()->id;
$servicios = App\Servicio::where('user_id',$user_id)->all();
return view('home', compact('servicios'));
}
the user will be present in your request, to make sure of that you should but
the route that use this method in (auth) middleware

Laravel 5.8 Search function in Restful API

I'm implementing an API for front end and mobile apps now i'm working on search function where a user may type column phone number or any data i should be able to provide the data they request in a JSON format
i really don't know how to query based on the data they input, so for i did this
My Controller,
public function searchMember(Request $request)
{
$data = $request->get('data');
$member_info = Member::where('phone_number', 'like', "%{$data}%")
->get();
return Response()->json([
'status' => 'success',
'data' => $member_info
], 200);
}
My Model,
class Member extends Model
{
protected $fillable = ['name','member_id','service_id','batch_id','phone_number','office_name','designation','email','image','remember_token'];
}
And my routes
Route::get('search?data=phone_number', 'MemberController#searchMember');
When I run the API resource its return 404 | not found.
I can not find the solution how to solve this.
In postman I run the API something like that:
http://localhost:8000/api/v1/search?data=0179826****
I know you solved your problem but just in case some one wants to know the answer. the correct way to pass data in url in rout is:
Route::get('search/{phone_number}', 'MemberController#searchMember');
and in your controller get it like:
public function searchMember(Request $request, $phone_number)
then your url would look like:
http://localhost:8000/api/v1/search/0179826****
other than that if you are going to send variable through request you don't need to clarify it in rout. so the route would be like:
Route::get('search', 'MemberController#searchMember');
the controller and the url would be as you posted.

how to get a post id using post link in laravel

Am trying to update a record in my database using an update button that is linked to a page where the update form is located but each time I click on the button, I get a 404 error (I think maybe the problem is that the page could not read the id of the requested post).
This is my route
Route::get('/pages/update/{id}','CallsController#edit');
Route::post('/pages/update/{id}','CallsController#update');
My CallsController
public function edit($id)
{
// $calls = Call::where('user_id', auth()->user()->id)->where('id', $id)->first();
// return view('pages.assignCall', compact('calls', 'id'));
$calls = Call::find($id);
return view('pages.assignCall')->with('calls', $calls);
}
public function update(Request $request, $id)
{
$calls = new Call();
$data = $this->validate($request, [
'call_details'=>'required',
]);
$data['id'] = $id;
$calls->updateCall($data);
return redirect('pages.pendingCalls');
}
I also have update.blade.php in the pages folder inside my views.
This is my update button
<a href="{{asset('/pages/update')}}>update</a>
You should not use the asset helpers to generate urls, but the url helpers. Also, you have to pass the id of the item you want to update. Because this is missing, you get a 404.
You should do something like this:
update
You can use laravel name route. If you use name route then your route should look like this
Route::get('/pages/update/{id}','CallsController#edit')->name('pages.update.view');
Route::post('/pages/update/{id}','CallsController#update')->name('pages.update');
And your update button should look like this
update

CakePHP user specific content on a single Dashboard

I have my Authentication setup in CakePHP to redirect all users to a dashboard using this function:
function dashboard() {
$group_name = $this->User->Group->field('name', array('id' => $this->Auth->User('group_id')));
$action = $group_name . '/dashboard/';
$this->redirect = array('controller' => 'users', 'action' => $action);
}
My question is what would be the best practice (or resource I can look at) to manage group-specific, and user-specific content within this dashboard
A model method that will fetch all the data you need in a single array with keys named like the view vars you want to use and set it from the controller to the view if you need to fetch different things that are not necessary associated.
If not simply return the data and set it to a view var like this:
public function dashboard() {
$this->set('artist', $this->Artist->dashboard($this->Auth->user('id')));
}
By passing the user id you can fetch whatever you need in the model through the associations.

Categories