Reference same variable using two controllers in laravel - php

I am generating a pdf based on user input. I can call the databse and get ALL contract info using all(). However, I would only like to generate a pdf for one of the values. Each contract has a auto incrememnt id which i could use.
Whats the best way to communicate between controllers so only the contract I am referencing is used to generate a pdf?
PdfGenerateController:
public function pdfview(Request $request)
{
$users = DB::table("users")->get();
$contract = Contract::all();
view()->share('users',$users);
if($request->has('download')){
// Set extra option
PDF::setOptions(['dpi' => 150, 'defaultFont' => 'sans-serif']);
$users = DB::table("users")->get();
// pass view file
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML
($contract);
return $pdf->stream();
}
return view('sell.contract');
}
Contract Controller (user input)
public function store(Request $request)
{
$contract = new Contract;
$contract->buyer_first_name = $request->input('buyer_first_name');
$contract->listing_id = $request->input('listing_id');
$contract->save();
return redirect()->route('generate-pdf')->with('contracts',$contract);
}

Storing the contract id in the session is probably your best bet. If you need to use it only on the next request, you could just flash it (in fact, that's exactly what the redirect(..)->withInput(sessionKey, val) does).
Something like that:
Contract Controller
public function store(Request $request)
{
// ...
$contract->save();
session(['contract_id' => $contract->id]);
return redirect()->route('generate-pdf');
}
Or just flashing:
public function store(Request $request)
{
// ...
$contract->save();
return redirect()->route('generate-pdf')->with('contract_id', $contract->id);
}
PdfGeneratteController
public function pdfview(Request $request)
{
$contract = Contract::findOrFail(session('contract_id'));
// ...
}

I would probably create a PDF model class with a static method to generate the PDF.
class PDF
{
public static function generatePDF($id, $isDownload)
{
// ...
}
}
Then you could simply call the static method from the Contact controller and pass the required data as parameters.
public function store(Request $request)
{
// ...
\PDF::generatePDF($contract->id, $request->has('download'));
// ...
}

Related

How to create a new request

I have a method that accepts a request
public function createUser(Request $request)
{
...
}
I want to call it from another method
public function someMethod(){
$array = [...];
return $this->createUser($array); <----
}
and how can I pass a new request to it with the array I need?
How about instead of trying to call a controller method, you move the logic to create a user to a service class and then use the service class in your createUser and someMethod methods?
UserService.php
class UserService
{
public function __construct() { }
public function createUser(array $userData)
{
// TODO use $userData to create a user here
return $newUser;
}
}
SomeController.php
public function createUser(Request $request)
{
$this->userService->createUser($request->all());
}
public function someMethod(){
$array = [...];
return $this->userService->createUser($array);
}

Laravel Dingo FindOrFail returns empty array

I have a table sites with list of sites with following columns ('id', 'path', 'site_link'). I've written in a Site model public $timestamps = false; so that it won't try to work with time what I don't need.
Also I have the following routes
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->get('sites', 'App\Http\Controllers\SiteController#index');
$api->get('sites/{site}', 'App\Http\Controllers\SiteController#show');
});
The first one is working fine and returning all the data, however the second one is returning just [].
I have a controller which is below
namespace App\Http\Controllers;
use Illuminate\Http\Request;
Use App\Site;
class SiteController extends Controller
{
public function index()
{
return Site::all();
}
public function show(Site $site)
{
return Site::findOrFail($site);
}
public function store(Request $request)
{
$site = Site::create($request->all());
return response()->json($site, 201);
}
public function update(Request $request, Site $site)
{
$site->update($request->all());
return response()->json($site, 200);
}
public function delete(Site $site)
{
$site->delete();
return response()->json(null, 204);
}
}
The show method in your SiteController is taking a Site object. However the route is set up to only take the siteId. The code below should work for you based on how you've set up your routes.
public function show($site)
{
return Site::findOrFail($site);
}
Apply same to all your other controller methods since you want pass the site id via the url to the controller methods.

Laravel: what's the better method to retrieve current logged user and why?

I know two method:
The first is using a Request object param in the controller's function
public function index(Request $request)
{
$user = $request->user();
return view('home');
}
The second is using directly the Auth facade.
public function index()
{
$user = Auth::user();
return view('home');
}
Are there any diferences? Are one method better that the other one and, if, yes, why?
This is only matter of preference, you can use:
public function index(Request $request)
{
$user = $request->user();
return view('home');
}
or
public function index()
{
$user = Auth::user();
return view('home');
}
or
public function index(Guard $auth)
{
$user = $auth->user();
return view('home');
}
or
public function index()
{
$user = auth()->user();
return view('home');
}
They will all work the same. There is no better or worse method for such simple piece of code.
In controller it doesn't make much difference but in case you write some services and you would like to test them (writing some unit tests for example), better solution would be in my opinion injecting Guard in constructor instead of running Auth facade or auth() helper.
The Auth facade provides a shortcut but the result is the same. You can always use \Auth::user() from your controller or views, on the other hand, if you want to use the $request variable, you need to pass it to your views.

what is the update method in laravel 5.4 crud?

i just trying to crud system. for that into controller store function my code is
public function store(Request $request)
{
Article::create([
'user_id' => auth()->id(),
'content' => $request->content,
'live' => (boolean)$request->live,
'post_on' => $request->post_on
]);
return redirect('/articles');
}
it's enough to store data, but when i want to edit article & save again then what will be my edit function code? i have no idea. i trying same code into edit function & it create new article not update. so what will be right code for edit function? thanks
Resource controller method for update is update(). Eloquent method for update() is update() too, so you can do this:
public function update(Request $request, $id)
{
Article::where('id', $id)->update($request->all());
return redirect('/articles');
}
You also can use the same controller and Eloquent method for both crerate and update data updateOrCreate() method.
You can also update it as object format like this.
public function update(Request $request, $id)
{
$article = Article::find($id);
$article->user_id = auth()->id();
$article->content = $request->content;
$article->live = (boolean)$request->live;
$article->post_on = $request->post_on;
$article->save();
}`
//route//
Route::any('/update/{id}', 'ProductController#update');
//controller//
public function update(Request $request, $id) {
$product = $request - > all();
Product::find($id) - > update($product);
return redirect('/product') - > with('message', 'Success', compact('product'));
}
you can use
public function update(Request $request, $id)
{
$article = Article::find($id);
$article->fill($request->all());
}
sure you should add Your column attributes to $fillable array in Your model
protected $fillable = ['user_id', 'content', 'live'];
public function update(Request $request, $id) {
Article::where('id', $id)->update($request->except(['_token']));
return redirect('/articles');
}
If you auto-generate resource controller for a specific Model using php artisan make:model -a Artical then you have the update() function like below:
public function update(Request $request, Article $article)
{
//
}
Here, Lavarel automatically fetch the Article object into $article. So, you can save the $request data like below:
public function update(Request $request, Article $article)
{
$article->update($request->all());
return redirect()->route('article.index'); // or your desired location :)
}
public function update(Request $request, $id)
{
$info = array('user_id' =>$request->user()->id,
'content' => $request->content, 'live'=>$request->live);
DB::table('article')->where('id', $id)->update($info);
session()->flash('success', 'Update Successfully');
return redirect('/article');
}
First, you are having two actions right, the create and update, so for a real crud in laravel you might have these two in a separated logic methods the store() and update():
/**
* This is a resource create method which is a HTTP POST.
*/
public function store(Request $request) {
// create a new item in database
}
/**
* This is a resource update which is a HTTP PUT METHOD.
*/
public function update(Request $request, $id) {
// update the item in database
}
You set up your routes withPOST for creating and PUT to update then your doing a proper crud resource.
I recommend you to separate the create logic off the update logic and if you have sort of unique data then you should validate its value before creating a new resource.

Arguement 1 must be instance of Illuminate\Http\Request integer given

When I am trying to send mail, everytime a new member is added to the user table, so that they can get a setup password link. I have been trying to get this to work but seem not to be.
public function store(AddUser $request)
{
$user = $request->all();
$user['activate'] = $this->active();
$user['guid'] = $this->guid();
$user['accountno'] = $this->generateAndValidateAccountno();
$check = User::find($user['phone']);
if(!$check) {
$id = User::create($user);
$this->sendEmail($user['accountno']);
}
return redirect('employee');
}
public function sendEmail(Request $request, $id)
{
$user = User::find($id);
Beautymail::send('emails.welcome', [], function($message)
{
$message
->to('$id->email', '$id->fname')
->subject('Welcome!');
});
}
}
Not sure what am doing wrong
Just use the same request class in the controller and the model. In your user model, add use Illuminate\Http\Request at the top of the class to tell it which Request class to use.
Just change:
public function sendEmail(Request $request, $id){...}
to
public function sendEmail($id){...}

Categories