Laravel model pass to view - php

Im using this library: https://www.laravelplay.com/packages/ycs77::laravel-wizard
I did all steps and have the same result like in the example.
Im trying to get data from database to each step.
Model (App/steps/intro/DropboxStep.php):
<?php
namespace App\Steps\Intro;
use Illuminate\Http\Request;
use Ycs77\LaravelWizard\Step;
use DB;
class DropboxStep extends Step
{
/**
* The step slug.
*
* #var string
*/
protected $slug = 'dropbox';
/**
* The step show label text.
*
* #var string
*/
protected $label = 'Dropbox';
/**
* The step form view path.
*
* #var string
*/
protected $view = 'steps.intro.dropbox';
/**
* Set the step model instance or the relationships instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation|null
*/
public function model(Request $request)
{
//
}
/**
* Save this step form data.
*
* #param \Illuminate\Http\Request $request
* #param array|null $data
* #param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation|null $model
* #return void
*/
public function saveData(Request $request, $data = null, $model = null)
{
//
}
/**
* Validation rules.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function rules(Request $request)
{
return [];
}
public function getOptions()
{
$stepa2 = DB::table('tutorials')->where('id', '2')->first();
return [
'stepa2' => $stepa2,
'Lucas',
];
}
}
View:
<div class="form-group">
{{ $stepa2 }}
</div>
Result:
Undefined variable: stepa2
Tried also through controller (IntroWizardController.php)
This is default controller:
<?php
namespace App\Http\Controllers;
use App\Steps\Intro\DropboxStep;
use App\Steps\Intro\H2NStep;
use App\Steps\Intro\PT4Step;
use Ycs77\LaravelWizard\Wizardable;
use DB;
class IntroWizardController extends Controller
{
use Wizardable;
/**
* The wizard name.
*
* #var string
*/
protected $wizardName = 'intro';
/**
* The wizard title.
*
* #var string
*/
protected $wizardTitle = 'Intro';
/**
* The wizard options.
*
* #var array
*/
protected $wizardOptions = [];
/**
* The wizard steps instance.
*
* #var array
*/
protected $steps = [
DropboxStep::class,
H2NStep::class,
PT4Step::class,
];
}
I added:
public function getOptions()
{
$stepa2 = DB::table('tutorials')->where('id', '2')->first();
return [
'stepa2' => $stepa2,
'Lucas',
];
}
Tried also in controller return to view, but then I get result from database in blank page, not with other parts.
Is it possible to pass database query to view with this library?
Thanks
EDIT:
With this routes:
Route::get('wizard/intro/dropbox', 'IntroWizardController#step1a', 'wizard.intro.dropbox');
Wizard::routes('wizard/intro', 'IntroWizardController', 'wizard.intro');
I get my result from database, but like I said before in white blank page:
But I want to get in this view like others (without query):

To pass any data from controller to blade view simply use these 2 options
option 1:
public function someFunction()
{
$model = DB::table('model_table')->where('id', '2')->first();
return view('blade_view_name', compact('model'));
}
option 2:
public function someFunction()
{
$model = DB::table('model_table')->where('id', '2')->first();
return view('blade_view_name')->with('model', $model);
}
if you have more or want more of variables you can chain the with() method like this:
return view('blade_view_name')
->with('model', $model)
->with('variable', 'Some other variable');

Related

Send a email with Laravel Nova Actions

I would like to send a mail from a button on Laravel Nova with an action (which I think is the most appropriate).
I already have a template of the mail saved in the mailable, I have made my resource but I don't know what to put inside since I need to retrieve information from this resource like for example the name, a price or the date when the line was created (in my table related to my resource).
My resource code:
<?php
namespace App\Nova;
use App\Image;
use Gloudemans\Shoppingcart\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Nova\Fields\Currency;
use Laravel\Nova\Fields\Date;
use Laravel\Nova\Fields\Heading;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
use Techouse\IntlDateTime\IntlDateTime;
class Order extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = \App\Order::class;
public static $group = 'Paramètres';
public static function label()
{
return __('Commandes');
}
public static function singularLabel()
{
return __('Commande');
}
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Nom du client', 'name'),
IntlDateTime::make('Passée le', 'created_at')
->locale('fr')
->readonly(),
Currency::make('Prix', 'total')->currency('EUR'),
Text::make('Mode de paiement', 'gateway')
->readonly(),
Text::make('Numéro de téléphone', 'phone'),
Heading::make('Adresse de livraison'),
Text::make('Adresse', 'address')
->hideFromIndex(),
Text::make('Code postal', 'postal_code')
->hideFromIndex(),
Text::make('Ville', 'city')
->hideFromIndex(),
Text::make('Pays', 'country')
->hideFromIndex(),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
My mailable code:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ResendOrder extends Mailable
{
use Queueable, SerializesModels;
/**
* Elements de contact
* #var array
*/
public $contact;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(Array $contact)
{
$this->contact = $contact;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orderconfirmation')
->subject("Confirmation de commande");
}
}
And finally my Action code:
<?php
namespace App\Nova\Actions;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
class EmailOrderConfirmation extends Action
{
use InteractsWithQueue, Queueable;
/**
* Perform the action on the given models.
*
* #param \Laravel\Nova\Fields\ActionFields $fields
* #param \Illuminate\Support\Collection $models
* #return mixed
*/
public $name = 'Renvoyer le mail de confirmation de commande';
public function handle(ActionFields $fields, Collection $models)
{
return Action::message('Mail envoyé');
}
/**
* Get the fields available on the action.
*
* #return array
*/
public function fields()
{
return [];
}
}
I don't really know where to go and what to use, if you could enlighten me on that I would be very grateful, thank you!
// in EmailOrderConfirmation --nova action
// declare what you are using
// use Illuminate\Support\Facades\Mail;
// use App\Mail\ResendOrder;
public function handle(ActionFields $fields, Collection $models)
{
//loop over the orders that have been selected in nova
foreach ($models as $order) {
$contact = $order->contract; //however you are getting contract data
//assuming you have a $order->user order belongs to user relationship
//send mail to the user, with the order/contract details to create your email
Mail::to($order->user->email)->send(new ResendOrder($contact));
}
//return a message to nova
return Action::message('Mail envoyé');
}
// in Order /Nova resource
// declare what you are using
// use App\Nova\Actions\EmailOrderConfirmation;
public function actions(Request $request)
{
return [new EmailOrderConfirmation];
}

Laravel Nova 404 when using hasMany

In my Laravel Nova project, I have a Page and a PageTranslation (model and resource). When adding a hasMany to my Resource fields, upon visiting the detail of the Page, I get a 404 error. This is my code
This is my Page Resource
<?php
namespace App\Pages\Resources;
use Illuminate\Http\Request;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\HasMany;
class Page extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = 'App\Pages\Models\Page';
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'working_title';
/**
* #var string
*/
public static $group = 'Pages';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id', 'working_title'
];
/**
* Eager load translations
*/
public static $with = ['translations'];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Title', 'working_title')
->sortable()
->rules('required', 'max:256'),
HasMany::make('Translations', 'translations', \App\Pages\Resources\PageTranslation::class)
];
}
}
This is my PageTranslation Resource
<?php
namespace Codedor\Pages\Resources;
use Illuminate\Http\Request;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
class PageTranslation extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = 'Codedor\Pages\Models\PageTranslation';
/**
* Hide resource from Nova's standard menu.
* #var bool
*/
public static $displayInNavigation = false;
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Locale')
->sortable()
->rules('required', 'max:256')
];
}
}
I'm a little bit late, but if anyone comes across this issue while using Nova::resources instead of the resources path inside resources method in NovaServiceProvider, make sure you add the related resource to the list.
If you wish to hide a resource from the sidebar navirgation, just use public static $displayInNavigation = false; inside the resource file
It's not related to relationships at all. Make sure you've included the resources in your NovaServiceProvider
Also, to restrict from viewing in the sidebar based on user role, you can do something like:
public static function availableForNavigation(Request $request)
{
return $request->user()->isAdmin();
}

Laravel: Can't get post form

Me and my partner have been working a combined period of almost 11 hours trying to figure this out but we just can't seem to crack it.
We're building a web forum application in which users are able to make their own threads. We managed to get edit to work, although redirect still doesn't work right yet. We have an online preview over at http://detune-niuwang.c9users.io/
If you try using the 'New Thread' page and click on the submit button, it will just delete anything typed into the form and checking back on the Frontpage, no threads would have been created. The Edit functionality works though.
Here are some snippets of our code:
Routes.php
Route::resource('posts', 'Channel\Post\Posts');
Route::get('/', 'Channel\Post\Posts#index');
Controllers\Channel\Post\Posts.php
/**
* Show the form for creating a new post.
*
* #return Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store the newly created post
*
* #param PostRequest $request
* #return Response
*/
public function store(PostRequest $request)
{
$postData = $this->post->create(['title', 'content']);
if($this->post->create($postData)) {
return redirect()->back()->withSuccess('Post successfully created.');
}
return redirect()->back()->withError($postData);
}
create.blade.php
#extends('_shared.master')
#section('title')
Create New Post
#endsection
#section('content')
<div class="panel panel-default">
<div class="panel-heading">New Thread</div>
<div class="panel-body">
{!! Form::open(['route' => 'posts.store', 'class' => 'form-horizontal'])!!}
#include('posts.form')
{!! Form::close() !!}
</div>
</div>
#stop
Models\Channel\Post\Post.php
<?php
namespace Detune\Models\Channel\Post;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* The database table used by the Model.
*
* #var string
*/
protected $table = 'posts';
/**
* The attributes that are mass assignable
*
* #var array
*/
protected $fillable = ['title', 'content', 'created_at'];
}
Repositories\PostRepository.php
<?php
namespace Detune\Repositories\Post;
use Detune\Models\Channel\Post\Post;
use Illuminate\Database\Eloquent\Collection;
/**
* Class PostRepository
* #Package Detune\Repository
*/
class PostRepository implements PostRepositoryInterface {
/**
* #var Post;
*/
protected $post;
/**
* #param Post $post
*/
public function __construct(Post $post)
{
$this->post = $post;
}
/**
* Create New Post
*
* #param array $postData
* #return Post|null
*/
public function create(array $postData)
{
return $this->post->create($postData);
}
/**
* Post Pagination
*
* #param array $filter
* #return collection
*/
public function paginate(array $filter)
{
return $this->post->paginate($filter['limit']);
}
/**
* Get Post by ID
*
* #param $id
* #return Post
*/
public function find($id)
{
return $this->post->find($id);
}
}
Repositories\PostRepositoryInterface.php
<?php
namespace Detune\Repositories\Post;
use Detune\Models\Channel\Post;
use Illuminate\Database\Eloquent\Collection;
/**
* Interface PostRepositoryInterface
* #package Detune\Repository
*/
interface PostRepositoryInterface {
/**
* Create New Post\
*
* #param array $postData
* #return Post
*/
public function create(array $postData);
/**
* Post Pagination
*
* #param array $filter
* #return collection
*/
public function paginate(array $filter);
/**
* Get Post by ID
* #param $post_id
* #return Post
*/
public function find($id);
}
Services\Post\PostService.php
<?php
namespace Detune\Services\Post;
use Detune\Services\Service;
use Illuminate\Contracts\Logging\Log;
use Illuminate\Support\ServiceProvider;
use Detune\Repositories\Post\PostRepositoryInterface;
/**
* Class PostService
* #package Detune\Services\Post
*/
class PostService extends Service {
/**
* #var PostRepositoryInterface
*/
protected $post;
/**
* #var Log
*/
protected $logger;
/**
* #param PostRepositoryInterface $post
* #param Log $logger
*/
public function __construct(PostRepositoryInterface $post, Log $logger)
{
$this->post = $post;
$this->logger = $logger;
}
/**
* Create New Post
*
* #param array $postData
* #return Post | null
*/
public function create()
{
try{
return $this->post->create($postData);
} catch (\Exception $e) {
$this->logger->error('Post->create: ' . $e->getMessage());
return null;
}
}
/**
* Post Pagination
*
* #param array $filter
* #return collection
*/
public function paginate(array $filter =[])
{
$filter['limit'] = 20;
return $this->post->paginate($filter);
}
/**
* Update the Post
*
* #param array $id
* #param array $postData
* #return bool
*/
public function update($id, array $postData)
{
try{
$post = $this->post->find($id);
$post->title = $postData['title'];
$post->content = $postData['content'];
return $post->save();
} catch (\Exception $e) {
$this->logger->error('Post->update: ' . $e->getMessage());
return false;
}
}
/**
* Delete Post
*
* #param $id
* #return mixed
*/
public function delete($id)
{
try {
$post = $this->post->find($id);
return $post->delete();
} catch (\Exception $e){
$this->logger->error('Post->delete: ' . $e->getMessage());
return false;
}
}
/**
* Get Post by ID
*
* #param $id
* #return Post
*/
public function find($id)
{
try {
return $this->post->find($id);
} catch (\Exception $e) {
$this->logger->error('Post->find: ' .$e->getMessage());
return null;
}
}
}
Any help with this are appreciated :)
The create method on an Eloquent model is normally a static method. In your code it seems to be called as if it's an instance method.
I believe you have (at least) 3 options.
Change your create call into an insert call. (I don't think this will return an instance of the Post model, just a boolean).
Call it statically Post::create($postData);
Use the newInstance method
$post = $this->post->newInstance($postData);
return $post->save() ? $post : null;

Middleware For actions into Controller, Laravel 5.1

I have a Controller that have a index method, but also have a multiple levels of users that have access to this method, but single the admin can view all records of the database How can i add a middleware for select the action corresponding to user? I have the next code
<?php
namespace SET\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use SET\Http\Requests;
use SET\Http\Requests\LabRequest;
use SET\Http\Controllers\Controller;
use Illuminate\Routing\Route;
use SET\Lab;
use Validator;
use Auth;
use DB;
class LaboratorioController extends Controller
{
public function __construct(){
$this->beforeFilter('#find', ['only' => ['show','edit','update','destroy']]);
}
public function find(Route $route){
$this->laboratorio = Lab::findOrFail($route->getParameter('laboratorio'));
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$labs = Lab::all();
return view('comp.lab.index',['labs' => $labs]);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return view('comp.lab.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(LabRequest $request)
{ Lab::create($request->all());
Session::flash('message','Laboratorio creado correctamente');
return Redirect::to('/laboratorio');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show()
{
$teams = $this->laboratorio;
return view('comp.lab.show',['lab'=>$this->laboratorio]);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit()
{
return view('comp.lab.edit',['lab'=>$this->laboratorio]);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update(LabRequest $request)
{
$this->laboratorio->update($request->all());
Session::flash('message','El laboratorio se actualizo correctamente');
return Redirect::to('/laboratorio');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy()
{
$this->laboratorio->delete();
Session::flash('message','El laboratorio fue eliminado correctamente');
return Redirect::to('/laboratorio');
}
Thanks :D
Here's a general idea:
$user_group = $user::get_user_group($user_id)
if($user_group->group_id === 'something'){
\\method to return data for group 'something'
}
Get data by groups
$user_data = $user::get_data_by_group_id($group_id)

Wrong instance passed in Laravel DB post request

So I am working on a page in Laravel that generates invite codes upon email submission. I have run into this issue, every time when I enter my email into the form, it is supposed to generate an invite code an input it into my DB then redirect me. Instead I get this error code:
Argument 1 passed to myapp\Repositories\Invite\EloquentInviteRepository::__construct()
must be an instance of Illuminate\Database\Eloquent\Model, instance of
Illuminate\Foundation\Application given, called in /var/www/laravel/bootstrap/compiled.php
on line 4259 and defined
This is my EloquentInviteRepository.php file, apparently line 21 is the line in error:
<?php namespace myapp\Repositories\Invite;
use myapp\Repositories\Crudable;
use Illuminate\Support\MessageBag;
use myapp\Repositories\Repository;
use Illuminate\Database\Eloquent\Model;
use myapp\Repositories\AbstractRepository;
class EloquentInviteRepository extends AbstractRepository implements Repository, Crudable, InviteRepository {
/**
* #var Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* Construct
*
* #param Illuminate\Database\Eloquent\Model $user
*/
public function __construct(Model $model)
{
parent::__construct(new MessageBag);
$this->model = $model;
}
/**
* Find a valid invite by a code
*
* #param string $code
* #return Illuminate\Database\Eloquent\Model
*/
public function getValidInviteByCode($code)
{
return $this->model->where('code', '=', $code)
->where('claimed_at', '=', null)
->first();
}
/**
* Create
*
* #param array $data
* #return Illuminate\Database\Eloquent\Model
*/
public function create(array $data)
{
$data['code'] = bin2hex(openssl_random_pseudo_bytes(16));
return $this->model->create($data);
}
/**
* Update
*
* #param array $data
* #return Illuminate\Database\Eloquent\Model
*/
public function update(array $data){}
/**
* Delete
*
* #param int $id
* #return boolean
*/
public function delete($id){}
}
In case anyone was curious; the __construct() interface from Illuminate\Database\Eloquent\Model.php:
/**
* Create a new Eloquent model instance.
*
* #param array $attributes
* #return void
*/
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
and Illuminate\Foundation\Application.php:
/**
* Create a new Illuminate application instance.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
public function __construct(Request $request = null)
{
$this->registerBaseBindings($request ?: $this->createNewRequest());
$this->registerBaseServiceProviders();
$this->registerBaseMiddlewares();
}
In case these help in debugging the issue!
As per request I have included my controller element used during the post function, this is the part that seems to activate the repository and prompt the error:
<?php
use myapp\Repositories\Invite\InviteRepository;
class InviteController extends BaseController {
/**
* InviteRepository
*
* #var myapp\Repositories\Invite\InviteRepository
*/
protected $repository;
/**
* Create a new instance of the InviteController
*
* #param myapp\Repositories\Invite\InviteRepository
*/
public function __construct(InviteRepository $repository)
{
$this->repository = $repository;
}
/**
* Create a new invite
*
* #return Response
*/
public function store()
{
$invite = $this->repository->create(Input::all());
}
}
RepositoryServiceProvider.php
<?php namespace myapp\Repositories;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider {
/**
* Register
*/
public function register()
{
$this->registerInviteRepository();
}
/**
* Register the Invite Repository
*
* #return void
*/
public function registerInviteRepository()
{
$this->app->bind('myapp\Repositories\Invite\InviteRepository', function($app)
{
return new EloquentInviteRepository( new Invite );
});
}
}
Any idea's as to what I am missing?
Thanks for the help guys,
You've been a great resource so far!
In the file RepositoryServiceProvider.php, replace this
$this->app->bind('myapp\Repositories\Invite\InviteRepository', function($app)
{
return new EloquentInviteRepository( new Invite );
});
With this:
$this->app->bind('myapp\Repositories\Invite\InviteRepository',
'myapp\Repositories\Invite\EloquentInviteRepository');

Categories