Global Value in laravel 5.6 - php

Here is my code ...
public function index()
{
$clientIP = request()->ip();
$cats=DB::table('catagory')->get();
$news=DB::table('news')->orderby('nID','desc')->limit('5')->get();
$books=DB::table('book')->where('bPrice','=',0)->orderby('bID','desc')->limit('5')->get();
return view('index',compact('clientIP','cats','news','books'));
}
As you see there are some variables, I passed them to my view but I have to repeat them in every view I wanna show.Is there any way to globalize them and use anywhere.Please help with sample code.Thanks.

Laravel view composer may help you.
You should add this code to your app/Providers/AppServiceProvider.php.
view()->composer(['index', 'index1', 'index2'], function($view) {
$clientIP = request()->ip();
$cats=DB::table('catagory')->get();
$news=DB::table('news')->orderby('nID','desc')->limit('5')->get();
$books=DB::table('book')->where('bPrice','=',0)->orderby('bID','desc')->limit('5')->get();
$view->with([
'clientIP' => $clientIP,
'cats' => $cats,
'news' => $news,
'books' => $books,
]);
});

Related

Problem with the function update() using Repository pattern to write REST API

I have a problem that all the create-read-delete using Repository Pattern is good but the update function is error. I still have the data but the information is not updated.
This is my code in EventController
public function update(EventRequest $request, $id)
{
$events = $this->repository->update($request->all());
return $this->sendResponse($events->toArray(), 'Successfully updated the Event!!');
}
This is i use DI for inject from the Repository, this is EventRepository.php
public function update($id, array $array) {
$events = $this->model->findOrFail($id);
$events->update($array);
return $events;
}
when i use dd($array) and the result returns [] without anything. Can anyone help me. Did i write anything wrong in this. Or i write the wrong Request
public function rules()
{
// $id = $this->events ? ',' . $this->events->id : '';
return $rules = [
'event_title' => 'required|max:255',
'event_type_id' => 'required|integer|between:1,3',
'from_date' => 'required|date_format:Y-m-d H:i:s',
'to_date' => 'date_format:Y-m-d H:i:s|nullable',
'is_recurring' => 'boolean|required',
'remarks' => 'nullable',
];
}
This method takes two arguments:
public function update($id, array $array) {
However, that's not how you are calling it:
$this->repository->update($request->all());
I take it $request->all() gives you an array, so pass the ID first.
$this->repository->update($id, $request->all());

Laravel Spark, Swap/Interact, and Private Variables

Using Laravel Spark, if I wanted to swap in a new implementation for the configureTeamForNewUser, at first it looks like it's possible because of the Spark::interact call here
#File: spark/src/Interactions/Auth/Register.php
Spark::interact(self::class.'#configureTeamForNewUser', [$request, $user]);
i.e. the framework calls configureTeamForNewUser using Spark::interact, which means I can Spark::swap it.
However, if I look at the configureTemForNewUser method itself
#File: spark/src/Interactions/Auth/Register.php
public function configureTeamForNewUser(RegisterRequest $request, $user)
{
if ($invitation = $request->invitation()) {
Spark::interact(AddTeamMember::class, [$invitation->team, $user]);
self::$team = $invitation->team;
$invitation->delete();
} elseif (Spark::onlyTeamPlans()) {
self::$team = Spark::interact(CreateTeam::class, [
$user, ['name' => $request->team, 'slug' => $request->team_slug]
]);
}
$user->currentTeam();
}
This method assigns a value to the private $team class property. It's my understanding that if I use Spark::swap my callback is called instead of the original method. Initial tests confirm this. However, since my callback can't set $team, this means my callback would change the behavior of the system in a way that's going to break other spark functionality.
Is the above a correct understanding of the system? Or am I missing something, and it would be possible to swap in another function call (somehow calling the original configureTeamForNewUser)?
Of course, you can swap this configureTeamForNewUser method. Spark create a team for a user at the registration. You have to add the swap method inside the Booted() method of App/Providers/SparkServiceProvider.php class.
in the top use following,
use Laravel\Spark\Contracts\Interactions\Auth\Register;
use Laravel\Spark\Contracts\Http\Requests\Auth\RegisterRequest;
use Laravel\Spark\Contracts\Interactions\Settings\Teams\CreateTeam;
use Laravel\Spark\Contracts\Interactions\Settings\Teams\AddTeamMember;
In my case I want to add new field call "custom_one" to the teams table. Inside the booted() method, swap the method as bellow.
Spark::swap('Register#configureTeamForNewUser', function(RegisterRequest $request, $user){
if ($invitation = $request->invitation()) {
Spark::interact(AddTeamMember::class, [$invitation->team, $user]);
self::$team = $invitation->team;
$invitation->delete();
} elseif (Spark::onlyTeamPlans()) {
self::$team = Spark::interact(CreateTeam::class, [ $user,
[
'name' => $request->team,
'slug' => $request->team_slug,
'custom_one' => $request->custom_one,
] ]);
}
$user->currentTeam();
});
In order to add a new custom_one field, I had to swap the TeamRepository#createmethod as well. After swapping configureTeamForNewUser method, swap the TeamRepository#create method onside the booted(),
Spark::swap('TeamRepository#create', function ($user, $data) {
$attributes = [
'owner_id' => $user->id,
'name' => $data['name'],
'custom_one' => $data['custom_one'],
'trial_ends_at' => Carbon::now()->addDays(Spark::teamTrialDays()),
];
if (Spark::teamsIdentifiedByPath()) {
$attributes['slug'] = $data['slug'];
}
return Spark::team()->forceCreate($attributes);
});
Then proceed with your registration.
See Laravel Spark documentation

how to pass two variables to view in controller (laravel 5.3)

I have two different queries which are saved in two variables.I want to pass the variables to view page from controller.
public function getApprovalList(){
// $users = select query..
// $request = select query..
return view('travelerHome',['users'=>$users,'request'=>$request]);
}
solution:
controller
return view('travelerHome',['users'=>$users,'requestList'=>$request]);
view
#foreach ($requestList as $req)
{{$req->traveler_name }}
#endforeach
return view('travelerHome')->with(array('users'=>$users,'request'=>$request));
You can use return view('travelerHome', compact('users', 'request')); too
Do like this
return view('travelerHome')->with('users'=>$users)->with('request'=>$request);
Code with you have written that is correct, you need to remove the comment only, I am also using the same method for pass the variable to View. Here is the example.
return view('admin.product.product.edit', ['product' => $product,
'attribute_set' => $productAttributes,
'category' => $cates,
'images' => $images,
'status' => $status,
'countries' => $countries,
'crane_manufacture' => $crane_manufacture,
'product_category' => $productCategory]);
}
And it's also working
So, in your code you need to
public function getApprovalList(){
$users = 'select query..';
$request = 'select query..';
return view('travelerHome',['users'=>$users,'request'=>$request]);
}

Yii 2 set up controller to accept json requests

I'm quite new to Yii 2 but here goes:
What I'm trying to accomplish is to set up a controller that simply reads in any json data posted to it.
I'm slightly confused as to how this works in Yii.
What I've tried so far is set up a controller called ftest to see if I could get it returning some json which seems to work:
public function actionFTest(){
$request = Yii::$app->request;
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'text/json');
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
$response->data = ['message' => 'Evan .. WHERE ARE YOU?'];
//$notificationData = json_decode(file_get_contents("php://input"), true);
//echo var_dump($notificationData);
}
Its a bit messy since I've been throwing in code back and forth. I know I should usually return something like $this->render(etc), but I'm not sure what I need to return as a view.
Thanks for any help you can provide
This might be helpful
use Yii;
use yii\web\Response;
public function actionFTest()
{
Yii::$app->response->format = Response::FORMAT_JSON;
}
Then after that just return a simple array like that:
return ['param' => $value];
Read this
http://www.yiiframework.com/doc-2.0/yii-web-response.html#$format-detail
I recommend you using behavior and contentNegotiator
public function behaviors()
{
return array_merge(
parent::behaviors(),
[
'contentNegotiator' => [
'class' => 'yii\filters\ContentNegotiator',
'formats' => [
'application/json' => \yii\web\Response::FORMAT_JSON,
]
]
],
);
}

Laravel 5.1 - Return to edit page

i'm writing a resource controller, and i have a problem with edit method.
i inserted a validator form, and if there is a error return to edit page with messages, but RETURN doesnt work good!
public function update(Request $request, $id)
{
$rules = [
'title' => 'required',
'content' => 'required',
'image' => 'required',
];
$messages = [
'title.required' => 'Campo titolo richiesto',
'content.required' => 'Contenuto richiesto',
'image.required' => 'Campo immagine richiesto',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()){
return redirect('admin/article/edit' , $id)->withErrors($validator);
}else {
$s = new Article;
$visible = (isset($_POST['visible']) == '1' ? '1' : '0');
$data = array(
'title' => $request->get('title'),
'slug' => $request->get('title'),
'content' => $request->get('content'),
'image' => $request->get('image'),
'user_id' => $request->get('user_id'),
'category_id' => $request->get('category_id'),
'visible' => $visible,
);
$s->where('id', '=', $id)->update($data);
return redirect('admin/article')->with('message', 'Articolo aggiornato con successo!');
}
}
It return to:
admin/article/edit/5
NOT to
admin/article/5/edit
How can i fix this issue? thank you for your help!
PS: $id work well, return my id edited
Here is the redirect helper. As you can see below, it takes status as its' second parameter.
function redirect($to = null, $status = 302, $headers = [], $secure = null)
What you do with passing the $id as the second parameter is actually setting the $status.
You need to pass the $to parameter as the full path like below.
return redirect('admin/article/' . $id . '/edit')->withErrors($validator);
I guess that you want to generate the url with route, which can be implemented like below.
return redirect(route('admin.article.edit', compact($id)))->withErrors($validator);
So you're saying the redirect on failure doesn't redirect to the right URL? Have you tried doing return redirect('admin/article/' . $id . '/edit')->withErrors($validator);?
I haven't tested this approach, but perhaps return redirect()->back()->withErrors($validator); could also work.
One way to do this, as others have suggested, is like following:
return redirect("admin/article/{$id}/edit")->withErrors($validator);
Or if you've a "Route Name" defined, like this..
return redirect()->route('route.name',[$id])->withErrors($validator);
it all depends on how you prefer, I prefer the later one, looks clean to me.
Easiest solution:
Laravel 5.1 has a back() helper, that returns to the previous page:
return back()->withErrors($validator);
More thorough explanation:
If you want to be more verbose, a generally more robust way to redirect to a route is to first define it as a named route in your routes.php:
Route::get('admin/article/{article_id}/edit', ['as' => 'articles.edit', 'uses' => 'ArticlesController#edit']);
Route::bind('article_id', function($id, $route) {
return App\Article::whereId($id)->findOrFail();
}
If you are using Route::resource instead, then this is already done automatically for you. To find the name of the route, run the command-line php artisan route:list. Then, in your controller method, you call it like this:
return redirect()->route('articles.edit', ['article_id' => $id])->withErrors($validator);
Using that kind of call, Laravel will automatically build the correct URL for you. This is more robust because if you ever want to change that URL to something else or change what controller method it calls, you only need to change it in one place, the routes.php, and not everywhere in your code (as long as every reference to that route in your code is referring to it by name).
Here you have
return redirect('admin/article/edit' , $id)->withErrors($validator);
means the link/route is admin/article/edit/$id(5 or 2 or ...)
better check
return redirect('admin/article/' . $id . '/edit')->withErrors($validator);
The redirect go to the passed url:
return redirect('admin/article/' . $id . '/edit'); #admin/article/id/edit
return redirect('admin/article/edit', $id); #admin/article/edit/5
And you can use methods to get this url:
return redirect(action('Controller#update', compact($id)));

Categories