Passing a GET value in route - php

I have this following Controllers on my file
class MyController1 extends BaseController{
public function notify($id,$message){
//Sending a push notification
//Google Cloud Messaging Here
//****//
}
}
How do i write the route to pass a value to id and message using GET?
Route::get("/sendMessage" , MyController1#notify);
the url should be something like
https://mysite.com/sendMessage?id=1&message=Hello
Also I need to call the notify method from other controllers like this. .
class MyController2 extends BaseController{
public function something(){
$con = new MyController2();
$con->notify($id,$message);
}
}
What should I put to the notify the model?

This is the code you need to create GET parameters in your URL:
Route::get('sendMessage/{id}/{msg}'
More information here:
http://laravel.com/docs/routing#route-parameters
Greetings

Laravel URL's work slightly differently to how you want it.
In Laravel as standard your URL for the above example will be
https://mysite.com/sendMessage/1/Hello
and your route would be
Route::get("/sendMessage/{id}/{message}" , MyController1#notify);
the text in the braces {} will be the name of the parameter passed to the controller function
eg. https://mysite.com/sendMessage/1/Hello would call MyController->notify(1,'Hello');

Related

Laravel, calling controller method from blade template file

Heey guys! I use Laravel 5.4, WAMP for localhost. I am struggling with the problem to call a Controller#methodName within my header.blade.php file, because I want to show in my header.blade.php file all notifications for the User. Normally I was getting all needed data with the help of routes in different pages. But for this case I need to call without using routes. Here is my code for my NotificationController:
class NotificationController extends Controller
{
public function getNotification(){
$notifications = Notification::where('user_id',Auth::user()->id)->get();
$unread=0;
foreach($notifications as $notify){
if($notify->seen==0)$unread++;
}
return ['notifications'=>$notifications, 'unread'=>$unread];
}
}
And I should receive all these data in my header file. I have used: {{App::make("NotificationController")->getNotification()}}
and {{NotificationController::getNotification() }} But it says Class NotificationController does not exist. Please heelp!
Instead of calling the controller method to get notifications, you can make a relationship method in your User model to retrieve all the notifications that belongs to the user and can use Auth::user()->notifications. For example:
// In User Model
public function notifications()
{
// Import Notification Model at the top, i.e:
// use App\Notification;
return $this->hasMany(Notification::class)
}
In your view you can now use something like this:
#foreach(auth()->user()->notifications as $notification)
// ...
#endforeach
Regarding your current problem, you need to use fully qualified namespace to make the controller instance, for example:
app(App\Http\Controllers\NotificationController::class)->getNotification()
Try using the full namespace:
For instance, App\Http\Controllers\NotificationController::getNotification
but of course, controllers aren't meant to be called the way you're using them. They're meant for routes. The better solution is to add a relationship in your user model like so:
public function notifications()
{
return $this->hasMany(Notification::class)
}
And then use this in your view like so:
#foreach(Auth::user()->notifications as $notification)

Laravel 5 / Lumen Request Header?

So I am not really sure how to go about this I have tried a few things and I will list one below however what I am trying to do is store information sent in a http request in a PHP variable.
Here is a view from Chrome Postman of me sending the request I want ot send. Note "pubapi" is a "header".
I have been messing around with Lumen requests as you can see documented here ( http://lumen.laravel.com/docs/requests ) and have tried using the following below to possibly display them but its not working obviously.
echo Request::all();
I am putting this in my controller and I have ...
use Illuminate\Http\Request;
in my controller.
So how could I say store the header I am sending "pubapi" into a php variable in my controller?
EDIT
Not sure if this will help, however looking at the Laravel frameworks docs I see this http://laravel.com/api/5.0/Illuminate/Http/Request.html#method_header trying this throws the same error in my code. So for example I tried the following and reached the same error.
echo Request::header('pubapi');
You misunderstand the Laravel request object on two levels.
First, the error you are getting is because you were referencing the object instead of the Facade. Facades have a way of forwarding static method calls to non-static methods.
Second, you are sending the value as a header but are trying to access the request parameters. This will never give you what you want.
Here is a simple way to see an example of what you want by creating a test route like so:
Route::match(['get','post'], '/test', function (Illuminate\Http\Request $request) {
dd($request->headers->all());
});
Post to this route and you will see your headers, one of which will be pubapi. Pay attention that the route method definition matches how you are submitting the request (ie GET or POST).
Let's apply this to the controller, ArticleController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
public function index(Request $request)
{
$pubapi = $request->header('pubapi'); // string
$headers = $request->headers->all(); // array
/*
$pubapi === $headers['pubapi']
*/
}
}
Try to change the Illuminate\Http\Request to Request.
- use Illuminate\Http\Request;
+ use Request;
Using
echo app('request')->header('pubapi');
Instead of
echo Request::header('pubapi');
Seemed to work perfect. Could someone provide additional explanation to why this worked and my original method didn't?
Actually you are calling it statically, that's why it is not getting appropriate Request class and throwing error, can do as follows
use Illuminate\Http\Request;
//inside your controller
class YourClass extends Controller{
public function yourFunction(Request $request){
//for getting all the request
dd($request->all());
//for getting header content
dd($request->header('pubapi'));
}
}
You can do it by request()->header('pubapi') also.
I prefer to use request() helper function than Request class its self. Because it can be used without use/import any class in the controller.

Using multiple controllers inside of one view

I Need some advice, as I'm still a bit new to Laravel and MVC in general. I'm coding a small web application that presents some data on the page, fetched from a remote API. However, the page already has a controller to it. The other controller I will be using I'm hoping I can also reuse it for other pages. I'm pretty stuck here.
So the two controllers
HomeController.php
ApiController.php
The HomeController is the original controller, which gets the view file (home.blade.php), with some other data that's being loaded from the controller.
With the ApiController, I want to fetch the api (json) results, do some changes and then load those changes to the HomeController as well. The changes would be like an array of methods and such that's being loaded to the view.
So How can I load both controllers inside of the same view?
First of all controllers doesn't get loaded inside view instead, you should load a view from a controller and to make the remote request for an API call you don't need to use another controller but you may use it if you have other use of API and need a separate controller. The flow is something like this:
class HomeController extends BaseController {
public function index()
{
// make the api call/remote request
// modify the returned data
// load the view
}
}
Let's rewrite it:
class HomeController extends BaseController {
protected $apiService = null;
public function __construct(ApiService $apiService)
{
$this->apiService = $apiService;
}
public function index()
{
// make the api call/remote request
$apiData = $this->apiService->makeRequest();
// modify the returned data.... then...
// load the view
return View::make(...)->with('apiData', $apiData);
}
}
So, it seems clear that, you should use the API related process in a separate class as a service, maybe a model or a simple repository class and inject it to your HomeController then use it from the controller.
Do all the API stuffs in ApiService and call methods of that class from the HomeController, in this case you may implement the ApiServiceRepository as a concrete class by implementing an interface, i.e. ApiService. So, finally it could be like this:
interface ApiService {
public function makeRequest();
}
// Implement the interface in concrete class
class ApiServiceRepository implements ApiService {
public function makeRequest()
{
// $data = make remote request
// return $data
}
}
Use the class HomeController with __construct as given above and add a IoC binding like:
App::bind('ApiService', 'ApiServiceRepository');
So, you don't have to worry about the dependency injection in the constructor of your HomeController.
BTW, to use a method from another controller, for example ApiController from HomeController you may use something like this:
$apiController = App::make('ApiController');
// Call any method of "ApiController" class/object
$apidata = $apiController->makeCallToMethod();
You may also check this article for understanding the use of repository pattern in Laravel.

Call function in Controller using URL

Im comming from CodeIgniter.
There if you had a controller like this:
class Article extends CI_Controller{
public function comments()
{
echo 'Look at this!';
}
}
You could access the comments() function using the URL like this: example.com/Article/comments
How could I do something similar in Laravel?
The way I do it right now is specifiying a route like this:
Route::get('/Article/comments}', 'ArticleController#comments');
But I was hoping for a more dynamic way to do it as I don't want to keep on creating new routes for every function
The recommended way of dynamically calling controllers methods via URL, for Laravel users, is via RESTful Controllers:
<?php
class ArticleController extends controller {
public function getComment()
{
return 'This is only accesible via GET method';
}
public function postComment()
{
return 'This is only accesible via POST method';
}
}
And create your route using telling Laravel this is a RESTful Controller:
Route::controller('articles', 'ArticlesController');
Then if you follow
http://laravel.dev/articles/comments
Using your browser, you should receive:
This is only accesible via GET method
The way you name your controllers methods (getComment, postComment, deleteComment...) tells Laravel wich HTTP method should be used to call those methods.
Check the docs: http://laravel.com/docs/controllers#restful-controllers
But you can also make it dynamic using PHP:
class ArticlesController extends Controller {
public function comments()
{
return 'Look at this!';
}
public function execute($method)
{
return $this->{$method}();
}
}
Use a controller like this one:
Route::get('Article/{method}', 'ArticleController#execute');
Then you just have to
http://laravel.dev/Article/comments
I'll recommend that you stick with the laravel's way to create REST controllers, because that way you can have control over what HTTP Verb is being called with the controller method. The laravel way of doing this is just to add the HTTP Verb in front of the controller method, for your method comments if you want to specify a GET request in Laravel the name of the method would look like getComments.
For example, if you need to do a GET request for the article/comments URI, and then to create a new comment you want to use the same URI with another HTTP verb, lets say POST, you just need to do something like this:
class ArticleController extends BaseController{
// GET: article/comments
public function getComments()
{
echo 'Look at this!';
}
// POST: article/comments
public function postComments()
{
// Do Something
}
}
Further reading:
http://laravel.com/docs/controllers#restful-controllers
Now for your specific answer, this is the Laravel way of doing what you requested:
class ArticleController extends BaseController{
public function getComments()
{
echo 'Look at this!';
}
}
and in the routes.php file you'll need to add the controller as follows:
Route::controller('articles', 'ArticleController');

Laravel routes with multiple optional parameters

I am building a RESTful api using Laravel. I am confused on how to do the routing.
I have the following api controller
class APIController extends BaseController{
public function sendMsg($authid, $roomid, $msg){
}
public function getMsg($roomid, $timestamp){
}
}
The URL format I want this to be accessible looks like this:
http://example.com/api/{functionName}/{parameter1}/{parameter2}/.../
Here, in the first parameter, I will have the function name which should map to the function in the controller class and following that the parameters the controller needs.
For example To access the sendMsg() function, the url should look like this:
http://example.com/api/sendMsg/sdf879s8/2/hi+there+whats+up
To access the getMsg() function, the url should look like
http://example.com/api/getMsg/2/1395796678
So... how can I write my routes so that it can handle the dynamic number and different parameters need?
I can write one route for each function name like so:
Route::get('/api/sendmsg/{authid}/{msg}', function($authid, $msg){
//call function...
});
and same for the other function. This if fine but is there a way to combine all function to the APIController in one route?
Yes, you can combine all the function to your APIController in one route by using a resourceful controller which is best suited for building an API:
Route::resource('api' ,'APIController');
But, technically, it's not one route at all, instead Laravel generates multiple routes for each function, to check routes, you may run php artisan routes command from your command prompt/terminal.
To, create a resourceful controller you may run the following command from your command line:
php artisan controller:make APIController
This will create a controller with 6 functions (skeleton/structure only) and each function would be mapped to a HTTP verb. It means, depending on the request type (GET/POST etc) the function will be invoked. For example, if a request is made using http://domain.com/api using GET request then the getIndex method will be invoked.
public function getIndex()
{
// ...
}
You should check the documentation for proper understanding in depth. This is known as RESTful api.

Categories