I'm using Laravel 4 and I'm trying to get the url bar to display the text url that is saved in the database instead of using the id.
This is my routes.php
Route::get('/{id}', function($id = 1){
if(is_numeric($id))
{
$page = Menu::find($id);
$action = 'content';
return App::make('HomeController')->$action($id);
} else {
$column = 'url';
$url = Seo::where($column, '=', $id)->get();
$action = 'show';
return App::make('HomeController')->$action($url[0]->id);
}
});
I'm also using a pivot table to link the menu to the seo.
Seo model
<?php
class Seo extends \Eloquent {
protected $fillable = array('url', 'meta_title', 'meta_description', 'keywords');
protected $guarded = array('id');
protected $table = 'seo';
public static $rules = array(
'title' => '',
'content' => '',
'image' => ''
);
public function menu(){
return $this->belongsToMany('Menu', 'menu_seo', 'seo_id', 'menu_id');
}
}
Menu model
<?php
class Menu extends \Eloquent {
protected $fillable = array('title', 'menu_id', 'image');
protected $guarded = array('id');
protected $table = 'menus';
public static $rules = array(
);
public function seo(){
return $this->belongsToMany('Seo', 'menu_seo', 'menu_id', 'seo_id');
}
}
HomeController
public function content($id)
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$menu = Menu::where('id', $id)->firstOrFail();
//dd($menu->frames);
return View::make('index', compact('menus_child'))->with('menu', $menu);
}
and then I call my views that references the menu like this
#foreach($menu->banner as $banners)
{{ $banners->title }}
#endforeach
I'm still not sure how you want to retrieve the correct URL associated to an id but that shouldn't really matter. The basic principle is just to fetch the URL and make a redirect:
Route::get('/{id}', function($id = 1){
if(is_numeric($id))
{
$page = Menu::find($id);
$url = 'foo'; // get correct URL somehow
return Redirect::to($url);
} else {
// ...
}
});
Related
I have this code in my controller:
public function store(StoreRequest $request)
{
$user = Auth::user();
$request->get('nombre');
$request->get('correo');
$request->get('creado_por');
$creado_por = Auth::user()->id;
$request->validate([
'creado_por' => 'string'
]);
return ComprasNotificacionCancelacion::create([
'nombre' => request('nombre'),
'correo' => request('correo')
]);
}
This is the model:
protected $table = 'compras_notificacion_cancelacions';
protected $primaryKey = 'id';
protected $guarded = ['id'];
protected $fillable = [
'nombre',
'correo',
'creado_por'
];
protected $dates = [
'fecha_creacion',
'fecha_modificacion'
];
Could you help me, please?
Your question is not clear, but what you are trying to do is add logged in user as the creado_por here is how you can achieve that.
public function store(StoreRequest $request)
{
$request->validate([
'creado_por' => 'string'
]);
//here you can use either Auth()->user()->id or $request->user()->id
return ComprasNotificacionCancelacion::create([
'nombre' => $request->nombre,
'correo' => $request->correo,
'creado_por' => $request->user()->id
]);
}
additionally here are somethings you could improve. You can access same Auth()->user() from $request like $request->user().
You don't need the below codes.
$user = Auth::user();
$request->get('nombre');
$request->get('correo');
$request->get('creado_por');
$creado_por = Auth::user()->id;
and if using id as id no need to mention it
protected $primaryKey = 'id';
The way I store the author of an entry is that I have a created_by column in the database and I make sure that contains the right ID inside the model. Here's a trait I use, that I call CreatedByTrait.php and use it on the models that need it:
<?php namespace App\Models\Traits;
use Illuminate\Database\Eloquent\Model;
trait CreatedByTrait {
/**
* Stores the user id at each create & update.
*/
public function save(array $options = [])
{
if (\Auth::check())
{
if (!isset($this->created_by) || $this->created_by=='') {
$this->created_by = \Auth::user()->id;
}
}
parent::save();
}
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function creator()
{
return $this->belongsTo('App\User', 'created_by');
}
}
I want to fetch the image from database as a URL like http://127.0.0.1:8000/uploads/category/image.png
but the result I am getting is the name of the file not the URL.
This is the model class:
class CategoryModel extends Model
{
protected $table="tb_category";
public $timestamps = false;
protected $fillable = [
'id',
'name',
'image'
];
}
This is my controller class:
class CategoryController extends Controller
{
//
public function viewPage(){
return view('category');
}
public function saveCategory(Request $request){
$category = new CategoryModel();
$category->name=$request->input('name');
if($request->hasfile('image')){
$file=$request->file('image');
$extension = $file->getClientOriginalExtension();
$filename=time().'.'.$extension;
//$headers = array('Content-Type' => 'application/octet-stream');
$file->move('uploads/category/',$filename);
$category->image =$filename;
$category->_image =$filename;
}
else{
return $request;
$category->image='';
$category->_image=null;
}
$category->save();
return view('category')->with('category',$category);
}
public function getCategories(){
$res = CategoryModel::get(
['id','name','image'
]
);
return response()->json($res,200);
}
}
In your saveCategory method, you're storing $filename in 'image' column.
Change it to store path.
public function saveCategory(Request $request){
$category = new CategoryModel();
$category->name=$request->input('name');
if($request->hasfile('image')){
$file=$request->file('image');
$extension = $file->getClientOriginalExtension();
$filename=time().'.'.$extension;
$file->move('uploads/category/',$filename);
$category->image ='http://127.0.0.1:8000/uploads/category/'.$filename; //This is where you need to save absolute path of the image.
}
else{
return $request;
}
$category->save();
return view('category')->with('category',$category);
}
One more problem here is that you've written code after return $request; in else statement. Any code written after return is unreachable for the interpreter and will not be executed.
i m about storing datas using haMany Relatiions
where Cars may have more than picture
and each picture can have only one car
Car Modem Car.php
class Car extends Model
{
protected $table = 'cars';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = array('Marque', 'Model', 'sieges', 'climatisation', 'portes', 'transmition', 'price','url','car_id');
public function cars_images()
{
return $this->hasMany(CarsImage::class);
}
CarsImage Model
class CarsImage extends Model
{
protected $table = 'cars_images';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = array('url');
public function cars()
{
return $this->belongsTo(Car::class);
}
}
MyController :
public function store(Request $request) {
$car = new Car;
$car->Marque = Input::get('Marque');
$car->Model = Input::get('Model');
$car->sieges = Input::get('sieges');
$car->climatisation = Input::get('climatisation');
$car->portes = Input::get('portes');
$car->transmition = Input::get('transmition');
$car->price = Input::get('price');
$img = new CarsImage;
$img->url = 'jean Luc Picard';
DB::transaction(function() use ($car, $img) {
$car = $car->save();
Car::find($car->id)->cars_images()->save($img);
});
return 'ok';
}
the problem is the car is saved and the url also is saved but with not the car_id
Any help please ?
just use create method:
$car = Car::create([
'Marque' => $request->Marque,
//other fields...
]);
$image = $car->cars_images()->create([
'url' => 'jean Luc Picard'
]);
and don't forget to use $fillable in your models.
$order_detail = Order::where([['user_id', $user->id], ['updated_at', '>', $updated_at]])
->with([
'currency' => function ($query) {
$query->select('currency_code', 'currency_symbol', 'ex_rate_with_base');
},
'orderList' => function ($query) {
$query->select('id', 'order_id', 'product_code', 'qty',
DB::raw('(unit_price*orders.ex_rate_with_base) as unit_price_new'), 'status');
},
])->get();
Please help,
How can I use the attribute ex_rate_with_base from order table in sub query.
I do not want to use DB query. Please solve it with eloquent.
I would have done it like this 👇
Database Structure:
ModelCurrency.php
class ModelCurrency extends Model
{
public $timestamps = true;
protected $table = 'currency';
protected $guarded = [];
}
ModelOrderList.php
class ModelOrderList extends Model{
public $timestamps = true;
protected $table = 'order_list';
protected $guarded = [];
}
ModelOrderDetail.php
class ModelOrderDetail extends Model{
public $timestamps = true;
protected $table = 'order_detail';
protected $guarded = [];
public function scopeOfUser($query, $user_id){
return $query->where('user_id', $user_id);
}
public function scopeUpdatedAfter($query, $updated_at){
return $query->where('updated_at', '>', $updated_at);
}
public function currency(){
return $this->hasOne(ModelCurrency::class, 'id', 'currency_id');
}
public function order_lists(){
return $this->hasMany(ModelOrderList::class, 'order_id', 'id');
}
}
Function in controller:
//imports
use App\ModelOrderDetail;
use Illuminate\Support\Carbon;
public function prices() {
$user_id = 1;
$updated_at = Carbon::yesterday();
$data = ModelOrderDetail::with('currency', 'order_lists')->ofUser($user_id)->updatedAfter($updated_at)->get();
foreach ($data as $d){
$base_rate = $d->currency->base_rate;
foreach($d->order_lists as $o) $o->new_unit_price = $base_rate * $o->unit_price;
}
return response()->json($data);
};
Edit - Output : https://pastebin.com/i53PytSk
I'm trying to get data from a column from table comment through the story table via the slug column. I've managed to do it with authors but I think I must be missing something or forgetting something because it is no longer working. I get this error
Exception in Collection.php line 1498: Property [comment] does not exist on this collection instance.
My controller function
public function slug($slug){
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$stories = Story::where('slug', $slug)->get();
$slug = $slug;
// I used this to get the author's email going through the slug from
// story table
$story = Story::with('author')->where('slug', $slug)->first();
$name = $story->author->first()->email;
// I would like to get the name in the comment table by going through
// the slug from the story table
$comment = Story::with('comment')->where('slug', $slug)->get();
$test = $comment->comment->first()->name;
return view('open::public.single-story', compact('menus_child', 'stories', 'slug'));
}
my Comment.php
namespace App\Modules\Authors\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = array('name', 'comment');
protected $guarded = array('id');
protected $table = 'comments';
//Validation rules
public static $rules = array(
'name' => '',
'comment' => ''
);
public function story(){
return $this->belongsToMany('App\Modules\Authors\Models\Story', 'comment_story', 'comment_id', 'story_id');
}
}
my Story.php
class Story extends Model
{
protected $fillable = array('title', 'content', 'type', 'slug');
protected $guarded = array('id');
protected $table = 'story';
//Validation rules
public static $rules = array(
'title' => '',
'content' => '',
'type' => ''
);
public function slug($title){
$this->attributes['title'] = $title;
$this->attributes['slug'] = Str::slug($title);
}
public function author(){
return $this->belongsToMany('App\Modules\Authors\Models\Author', 'author_story', 'story_id', 'author_id');
}
public function comment(){
return $this->belongsToMany('App\Modules\Authors\Models\Comment', 'comment_story', 'story_id', 'comment_id');
}
}
With some help from dparoli I managed to do it. I can't believe it to me so long to figure it out.
I changed
$comment = Story::with('comment')->where('slug', $slug)->get();
$test = $comment->comment->first()->name;
to
$comment = Story::with('comment')->where('slug', $slug)->first();
$test = $comment->comment->toArray();
and I added test to
return view('open::public.single-story', compact('menus_child', 'stories', 'slug', 'test'));
and then added
#foreach($test as $t)
<h1>{!! $t['name'] !!}</h1>
<p>{!! $t['comment'] !!}
#endforeach
to my view
Try to change this:
//here you get a collection of stories
$comment = Story::with('comment')->where('slug', $slug)->get();
To this:
//here you get a single story
$comment = Story::with('comment')->where('slug', $slug)->first();
I give you a different approach to try
$comments = Comment::with(['story' => function ($query) {
$query->where('slug', '=', $slug);
}])->get();
Give this a go if it works for what you are trying to accomplish.