How to pass variable from blade to LARAVEL commands - laravel

I need to pass user_id from blade to routes, and then use the variable into a laravel command. How can I do?
lista_lavori.blade.php
<div class="box-tools">
<i class="fa fa-print"></i>
</div>
web.php - route
Route::get('/stampasingoloreport/{id}', function ($id) {
Artisan::call('StampaSingoloReport:stampasingoloreport');
return back();
});
StampaSingoloReport.php - Commands
public function handle()
{
// static id i need to change this dinamically
$id = 5;
$utente = \App\User::where('id',$id)->get();
//invio email per avvertire l'utente
$data = array('utenti'=>$utente);
Mail::send('mail.invioMailReportLavoriSingoli', $data, function($message) {
$message->to('rubertocarmine94#gmail.com', 'Admin Risorse Umane') ->subject('Email da piattaforma BancaStatoHR') ;
$message->from('rubertocarmine94#gmail.com') ;
});
}

You can pass an array to call() method like
Route::get('/stampasingoloreport/{id}', function ($id) {
Artisan::call('StampaSingoloReport:stampasingoloreport',[
'id' => $id
]);
return back();
});
Now in your handle method, you can access these arguments like
protected $signature = 'StampaSingoloReport:stampasingoloreport { id } ' ;
function handle(){
$this->argument('id');
// your code
}
Hope this helps

Related

send an email in Laravel on a create function

send an email in Laravel on a create function but not able to do
this is my store function
public function store()
{
$input = $request->all();
$user = \AUTH::guard()->user();
$input['created_by'] = $user->id;
\Log::info('$input'.json_encode([$input]));
$bulkLabSample = $this->bulkLabSampleRepository->create($input);
Flash::success(__('messages.saved', ['model' => __('models/bulkLabSamples.singular')]));
return redirect(route('bulkLabSamples.index'));
}
// use this
use Illuminate\Support\Facades\Mail;
// send mail via mail
Mail::send('your-view-blade', ['extraInfo' => $extraInfo], function ($message) {
$message->to('email#email.com');
$message->subject('your subject here');
});
By extraInfo you can pass values to the mail template as you want.
// for your code
public function store()
{
$input = $request->all();
$user = \AUTH::guard()->user();
$input['created_by'] = $user->id;
\Log::info('$input'.json_encode([$input]));
$bulkLabSample = $this->bulkLabSampleRepository->create($input);
Mail::send('your-view-blade', ['extraInfo' => $extraInfo], function ($message) {
$message->to('email#email.com');
$message->subject('your subject here');
});
Flash::success(__('messages.saved', ['model' => __('models/bulkLabSamples.singular')]));
return redirect(route('bulkLabSamples.index'));
}

Laravel: Accessing Path Function in Model in Index File

I have set up the following function in my model:
public function path() {
return route('news.show', ['id' => $this->id, 'slug' => $this->slug]);
}
I would now like to access that function in my index.blade.php file -- like this:
#foreach ($articles as $article)
<a href="{{ $article->path() }}">
// rest of code goes here
</a>
#endforeach
But when I try this, I get the following error:
Facade\Ignition\Exceptions\ViewException
Missing required parameters for [Route: news.show] [URI: news/{id}/{slug}]. (View: C:\laragon\www\startup-reporter\resources\views\news\index.blade.php)
Here is what my routes (web.php) looks like:
Route::get('news', 'NewsController#index')->name('news.index');
Route::get('news/create', 'NewsController#create')->name('news.create');
Route::get('news/{id}/{slug}', 'NewsController#show')->name('news.show');
Route::get('news/{id}/edit', 'NewsController#edit')->name('news.edit');
Route::post('news', 'NewsController#store')->name('news.store');
Route::put('news/{id}', 'NewsController#update');
And here is my controller:
// Index
public function index() {
$news = News::latest()->get();
return view('news.index', ['articles' => $news]);
}
// Show
public function show(News $id) {
return view('news.show', compact('id'));
}
Any idea why this is not working and what I need to do to get this to work?
Thanks.
In your routes file you have defined 2 parameters, {id} and {slug}.
But in your controller you have only accepted 1 parameter, $id.
You should amend your show controller method like this:
// Show
public function show(News $id, $slug) {
return view('news.show', compact('id'));
}

Why does the old() method not work in Laravel Blade?

My environment is Laravel 6.0 with PHP 7.3. I want to show the old search value in the text field. However, the old() method is not working. After searching, the old value of the search disappeared. Why isn't the old value displayed? I researched that in most cases, you can use redirect()->withInput() but I don't want to use redirect(). I would prefer to use the view(). method
Controller
class ClientController extends Controller
{
public function index()
{
$clients = Client::orderBy('id', 'asc')->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
public function search()
{
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
$query = Client::query();
if (isset($clientID)) {
$query->where('id', $clientID);
}
if ($status != "default") {
$query->where('status', (int) $status);
}
if (isset($nameKana)) {
$query->where('nameKana', 'LIKE', '%'.$nameKana.'%');
}
if (isset($registerStartDate)) {
$query->whereDate('registerDate', '>=', $registerStartDate);
}
if (isset($registerEndDate)) {
$query->whereDate('registerDate', '<=', $registerEndDate);
}
$clients = $query->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
}
Routes
Route::get('/', 'ClientController#index')->name('client.index');
Route::get('/search', 'ClientController#search')->name('client.search');
You just need to pass the variables back to the view:
In Controller:
public function search(Request $request){
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
...
return view('auth.client.index', compact('clients', 'clientID', 'status', 'nameKana', 'registerStartDate', 'registerEndDate'));
}
Then, in your index, just do an isset() check on the variables:
In index.blade.php:
<input name="clientID" value="{{ isset($clientID) ? $clientID : '' }}"/>
<input name="status" value="{{ isset($status) ? $status : '' }}"/>
<input name="nameKana" value="{{ isset($nameKana) ? $nameKana : '' }}"/>
...
Since you're returning the same view in both functions, but only passing the variables on one of them, you need to use isset() to ensure the variables exist before trying to use them as the value() attribute on your inputs.
Also, make sure you have Request $request in your method, public function search(Request $request){ ... } (see above) so that $request->input() is accessible.
Change the way you load your view and pass in the array as argument.
// Example:
// Create a newarray with new and old data
$dataSet = array (
'clients' => $query->paginate(Client::PAGINATE_NUMBER),
// OLD DATA
'clientID' => $clientID,
'status' => $status,
'nameKana' => $nameKana,
'registerStartDate' => $registerStartDate,
'registerEndDate' => $registerEndDate
);
// sent dataset
return view('auth.client.index', $dataSet);
Then you can access them in your view as variables $registerStartDate but better to check if it exists first using the isset() method.
example <input type='text' value='#if(isset($registerStartDate)) {{registerStartDate}} #endif />

laravel send parameter in route

Is thier anyway to do somethins like this ,
in web.php
Route::get('/test', 'testController#test');
in test Controller
public function test ($url)
{
//while $url store test in route
}
I know only if I send parameter I have to use
Route::get('/{test}', 'testController#test');
UPDATE
I want to do something like this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
in my controller
public function test ($url)
{
while $url store test,test2in route
}
LASTEST UPDATE
I dont want to use {url}
I want to make /test = $url when I enter to url/test
In my web.php I use this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
The reason that I want to do something like this because I want to make 1 function that alll route can use In my controller I do this .
public function test($url,$preview=null)
{
//$url shoud be test or test 2
try {
$test = (isset($preview)) ? test::where('test.id',$url)->first()
} catch (\Exception $e) {
return redirect('notfound');
}
}
I dont want todo something like this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
and In controller
public function test($preview=null)
{
//$url shoud be test or test 2
try {
$test = (isset($preview)) ? test::where('test.id','test)->first()
} catch (\Exception $e) {
return redirect('notfound');
}
}
You need to combine both elements
Route::get('/test/{url}', 'testController#test');
want to make /test = $url
You can't, but you can have /test?foo=$url instead. So you keep your route like
Route::get('/test', 'testController#test');
Then add Request $request as controller method argument (and you remove $url)
public function test(Request $request) {
...
Finally you obtain your url with
$url = $request->input('foo');
Your Route
Route::post('/test', 'testController#test')->name('test);
If you use blade.
<a href="{{ route('test') }}"
onclick="event.preventDefault();
document.getElementById('test_id').submit();">
Test Click
</a>
{!! Form::open(['url' => route('test'), 'method' => 'post', 'id' => 'test_id']) !!}
<input type="hidden" name="url" value="{{ $url}}">
{!! Form::close() !!}
In your controller.
public function test(Request $request)
{
$data = $request->all();
$url = $data['url'];
//do something with your url...
}

Keeping modal dialog open after validation error laravel

So basically I have a blade.php, controller page and a form request page(validation). I'm trying to keep my modal dialog open if there is an error but I just cant figure it out, what part of code am I missing out on or needs to be changed?
blade.php
<div id="register" class="modal fade" role="dialog">
...
<script type="text/javascript">
if ({{ Input::old('autoOpenModal', 'false') }}) {
//JavaScript code that open up your modal.
$('#register').modal('show');
}
</script>
Controller.php
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function register(StoreNewUserRequest $request)
{
// process the form here
$this->userRepository->upsert($request);
Session::flash('flash_message', 'User successfully added!');
//$input = Input::except('password', 'password_confirm');
//$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
return redirect()->back();
}
}
class UserRepository {
public function upsert($data)
{
// Now we can separate this upsert function here
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}
request.php
class StoreNewUserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
// create the validation rules ------------------------
return [
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the user table
'password' => 'required|min:8|alpha_num',
'password_confirm' => 'required|same:password', // required and has to match the password field
'mobile' => 'required',
'role_id' => 'required'
];
}
}
Laravel automatically checks for errors in the session data and so, an $errors variable is actually always available on all your views. If you want to display a modal when there are any errors present, you can try something like this:
<script type="text/javascript">
#if (count($errors) > 0)
$('#register').modal('show');
#endif
</script>
Put If condition outside from script. This above is not working in my case
#if (count($errors) > 0)
<script type="text/javascript">
$( document ).ready(function() {
$('#exampleModal2').modal('show');
});
</script>
#endif
for possibly multiple modal windows you can expand Thomas Kim's code like following:
<script type="text/javascript">
#if ($errors->has('email_dispatcher')||$errors->has('name_dispatcher')|| ... )
$('#register_dispatcher').modal('show');
#endif
#if ($errors->has('email_driver')||$errors->has('name_driver')|| ... )
$('#register_driver').modal('show');
#endif
...
</script>
where email_dispatcher, name_dispatcher, email_driver, name_driver
are your request names being validated
just replace the name of your modal with "login-modal". To avoid error put it after the jquery file you linked or jquery initialized.
<?php if(count($login_errors)>0) : ?>
<script>
$( document ).ready(function() {
$('#login-modal').modal('show');
});
</script>
<?php endif ?>

Resources