Laravel 5.4 Add a difference between views - laravel

I use the same view to show one post and random post
routes
Route::get('posts/{id}', 'PostsController#show')->name('posts.show');
Route::get('get-random-post', 'PostsController#getRandomPost');
methods in PostsController
public function show($id) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
return redirect()->route('posts.show', ["id" => $post->id]);
}
but now I need to add a small difference between two views. How can I do that?
UPD
I added variable $randomPost to methods in Controller
public function show($id) {
$randomPost = false;
$post = Post::findOrFail($id);
return view('posts.show', compact('post', 'randomPost'));
}
public function getRandomPost() {
$randomPost = true;
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
return redirect()->route('posts.show', ["id" => $post->id]);
}
and added code below to show view
#if($randomPost)
some text
#endif
but I don't know how to pass variable from getRandomPost() to view?
UPD2
As result I used session, it works but I'm not sure about it
method
public function getRandomPost() {
$post = Post::inRandomOrder()
->where('is_published', 1)->first();
session()->flash('random_post', 'ok');
return redirect()->route('posts.show', ["id" => $post->id]);
}
view
#extends('layouts.app')
#section('content')
Home page
<h2>#{{$post->id}}</h2>
{!! nl2br(e($post->text)) !!}
<?php if(session()->has('random_post')){
echo '<div style="text-align: center">';
echo link_to_action('PostsController#getRandomPost', 'Random Post', $parameters = array(), $attributes = array());
echo '</div>';
}?>
#stop

You can use session flash, it lasts only on subsequent request:
// set
session()->flash('random_post', 'ok');
// check
if(session()->has('random_post')){
// is random

I guess the easiest way would be to call the function from the getRandomPost by passing a default variable through.
public function show($id, $randomPost = false) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post', 'randomPost'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()->where('is_published', 1)->first();
$this->show($post->id, true);
}

Related

get page number in object of laravel

i have object given below and i wanted to pagination in this how can i get
$productListArray = array();
$productListObject = ((object)[
"id"=>$productList->id,
"title"=>$productList->title,
"slug"=>$productList->slug,
'categoryName'=>$categoryName[0]->cat_title,
'brand'=>$brandName[0]->brandname,
'minMrp'=>$minMrp,
'maxMrp' =>$maxMrp,
'minSellingPrice' => $minSellingPrice,
'maxSellingPrice' => $maxSellingPrice,
'rating'=>$productList->rating,
'rating_count' => $productList->rating_count,
'image' => $img[0]
])->paginate();
array_push($productListArray, $productListObject);
}
return response()->json($productListArray, 200);
Hi you can get the Current page using laravel paginator Paginator::currentPageResolver
public function index()
{
$currentPage = 3; // You can set this to any page you want to paginate to
// Make sure that you call the static method currentPageResolver()
// before querying users
Paginator::currentPageResolver(function () use ($currentPage) {
return $currentPage;
});
$users = \App\User::paginate(5);
return view('user.index', compact('users'));
}
thanks for your support i found solution,
first add on your header
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
then make an other function
public function paginate($items, $perPage = 5, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
after than call this function where you want in class
$data = $this->paginate($productListArray);
return response()->json($data, 200);
last 2 lines already mentioned in my questions
thanks again

How to select specfic id and update in Laravel?

I'm studing Laravel CRUD.
Laravel Framework is 6.18.15
I would like to select of a record and update.
This is photo gallery.
Now if I click one of photo I can get below URL
https://mywebsite.net/public/edit?id=59
but in edit.blade.php I got this error
Undefined variable: id
Could someone teach me correct code please?
These are current code
Controller UPDATED
public function edit(Request $request)
{
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
public function editpcs(Request $request)
{
$this->validate($request, [
'title' => 'required',
'image' => 'required|mimes:jpeg,jpg'
]);
$input['image'] = time().'.'.$request->image->getClientOriginalExtension();
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time().'.'.$request->image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1280, null, function ($image) {$image->aspectRatio();});
$image_resize->save(public_path('images/ServiceImages/' .$filename));
}
$request->image->move(public_path('images'), $input['image']);
$input['title'] = $request->title;
// ImageGallery::update($input);
$update = DB::table('image_gallery')->where('id', $id)->update( [ 'title' => $request->title, 'image' => $request->image]);
return view('edit',compact('images'))->with('sucess','sucessfully updated');
}
web.php
//edit view
Route::get('edit', 'ImageGalleryController#edit');
Route::post('edit', 'ImageGalleryController#edit');
//edit procces
Route::get('editpcs', 'ImageGalleryController#editpcs');
Route::post('editpcs', 'ImageGalleryController#editpcs');
UPDATE
#if($images->count())
#foreach($images as $image)
<div class='text-center'>
<small class='text-muted'>{{$image['id']}}/ {{$image['title']}} </small>
</div>
#endforeach
#endif
MODEL
namespace App;
use Illuminate\Database\Eloquent\Model;
class ImageGallery extends Model
{
protected $table = 'image_gallery';
protected $fillable = ['title', 'image'];
}
Actually $id is really undefined here, it would be $request->route('id') or request('id') or $_GET['id'] or $request->input('id') :
public function edit(Request $request)
{
$id = request('id');
$images = ImageGallery::findOrFail($id); // use findOrFail() id not exist in table, it throw a 404 error
return view('edit',compact('images'));
}
Take a look at the $_GET and $_REQUEST superglobals. Something like the following would work for your example:
$id = $_GET['id'];
$country = $_GET['country'];
In laravel you can to use Input::get(), But Input::get is deprecated in newer version of laravel, prefer the $request->input instead of Input::get :
$id= $request->input('id');
$country= $request->input('country');
It looks to me like this function:
public function edit(Request $request)
{
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
Should be something like this perhaps?
public function edit(Request $request)
{
$id = $request->input('id', null);
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
As it is, $id appears to be undefined before you attempt to pass it into the find() method. But according to your URL it is in the $request object. So you need to get it from there and into the function. You can read about this method in the docs.
public function edit(Request $request)
{
$id = request('id');
$images = ImageGallery::where('id',$id)->first();
return view('edit',compact('images'));
}

Codeigniter: Display an image stored in DB

How do I get an image stored in a field of my database, and put it into a variable for using it in an email message like a signature?
Here is my code:
//Model user_model
function getImage(){
$this->db->select("image");
$this->db->where("$id", user_id);
$query = $this->db->get("users");
if($query->num_rows()>0){
return result();
}else{
return false;
}
}
//Controller user_controller
function image(){
this->load->model("user_model");
$id = $this->session->userdata('id');
$image = $this->user_model->getImage($id);
echo $image;
}
Here is a example
Model user_model
// Pass the id function
function getImage($id){
$this->db->where($id, 'user_id');
$query = $this->db->get("users");
if($query->num_rows()>0){
return $query->row_array();
}else{
return false;
}
}
Controller user_controller
function image(){
$this->load->model("user_model");
$somedata = $this->user_model->getImage($this->session->userdata('id'));
$data['image'] = $somedata['image'];
$this->load->view('someview', $data);
}
On view
<?php echo $image;?>

How to Share functions in same controller in one view

Hi i have a Controller called homeController and a view called home.blade.php (home). I have 2 functions in my homeController that i want to use in my view 'home'.
The function called index() , works fine, but how do i get the values from function userchart() to my view 'home'.
public function index(){
$value1 = '';
$value2 = '';
return view('home', compact('$value1', 'value2'));
}
public function userchart(){
$value3 = '';
$value4 = '';
return view('home', compact('$value3', 'value4'));
}
Now in my VIEW i can only access $value1 and $value2
foreach($value1 as $key){
echo $key->value;
}
How do i get access to the data '$value3 and $value4'
public function index(){
$data['value1'] = 'value1';
$data['value2'] = 'value2';
$data = array_merge($data, $this->userchart());
return view('home', $data);
}
public function userchart(){
$data['value3'] = 'value3';
$data['value4'] = 'value4';
return $data;
}

Laravel - update one to one field

I have an update post form, where I need to update the name of the post in posts table and the associated text within the text table. I can't seem to get it to work at all.
Model - Post.php
public function text()
{
return $this->hasOne('Text');
}
Model - Text.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function updateQuestionForm($id)
{
$post = Post::find($id);
$input = Input::all();
$rules = array(
'text' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::back()->withErrors($validation)->withInput();
} else {
$post->title = Input::get('title');
$post->save();
$text = $post->text();
$text->text = Input::get('text');
$post->text()->save($text);
$message = "Post updated";
return Redirect::to('question/'.$post->id.'/'.$post->slug.'/')->with('message', $message);
}
}

Resources